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:


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


Using grep:

grep -o '.*Exception' file

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

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
| improve this answer | |
  • 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 – abadawi Feb 4 '19 at 5:11
  • @abadawi: That should be an edit to your question or possibly even a new question altogether but I have updated my answer. – jesse_b Feb 4 '19 at 13:40
  • Thanks a bunch! That's exactly the behavior I was looking for – abadawi Feb 5 '19 at 4:59

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.

| improve this answer | |

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
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.