grep everything up until and including a pattern

5,733

Solution 1

Using grep:

grep -o '.*Exception' file

-o, --only-matching
Prints only the matching part of the lines.

'.*Exception'
This will match between 0 and unlimited occurrences of any character (except for line terminators) up until the word "Exception"


In order to get the behavior you mentioned in the comment (pull the string before and including Exception up until any leading whitespace) you can use extended or perl regex to use the \S control character (any non-whitespace character):

grep -oE '\S+Exception' file

Solution 2

With POSIX utilities (so will work with GNU and non-GNU implementations):

everything up to the first occurrence of Exception on a line:

sed -n 's/\(Exception\).*/\1/p'

everything up to the last occurrence:

sed -n 's/\(.*Exception\).*/\1/p'

Remove the -n and p if you want to preserve (unmodified) the lines that don't contain Exception.

Solution 3

With your favorite standard editor, ed:

ed -s input <<< $'1,$s/Exception.*/Exception/\nw\nq'

This edits the input file input with a here-string list of commands, namely:

  1. 1,$ -- on every line in the file (1 through the end $),
  2. s/Exception.*/Exception/ -- search and replace the string "Exception" followed by anything (.*) with just the word "Exception"
  3. w -- write the file back to disk
  4. q -- quit ed
Share:
5,733

Related videos on Youtube

abadawi
Author by

abadawi

Updated on September 18, 2022

Comments

  • abadawi
    abadawi over 1 year

    Let's assume I have a log file that contains exceptions as shown

    java.lang.NullPointerException blabla
    ABC.Exception blalabbla
    dogchacecat.Exception yadayada
    

    I want to be able to output each line from beginning and up until (including) "Exception"

    desired output:

    java.lang.NullPointerException
    ABC.Exception
    dogchacecat.Exception
    

    How do I do this using any GNU tool (grep, awk, sed)? Thank you!

  • abadawi
    abadawi over 5 years
    What if I want to print only the contiguous non-empty sequence of words, chars or dots that come before ".Exception"? so that when I have input as: bla bla bla java.lang.NullPointerException yada yada yada it only prints: java.lang.NullPointerException Thanks @Jesse_b
  • jesse_b
    jesse_b over 5 years
    @abadawi: That should be an edit to your question or possibly even a new question altogether but I have updated my answer.
  • abadawi
    abadawi over 5 years
    Thanks a bunch! That's exactly the behavior I was looking for