0

I have a huge log file and want to search for the text "exception threw by :: " from the end of the file and get couple more characters from there. Basically I am interested in the last occurrence only.

for example if the log file is like

some data exception threw by :: classA some more text exception threw by :: classBB some other logs recent ones exception threw by :: classX

I want to find and print exception threw by :: classX

Kindly help.

  • Does "threw by :: classX" always appear on one line? Is the log file line by line or a single line? – gogators Oct 27 '15 at 20:52
1

This will search for the text you want $TEXT from the log data.txt, show X lines before and show Y lines after the match. The tail command will filter out all but the last match. The number used in the tail command is Z, and Z = X + Y + 1

grep -BX -AY "$TEXT" data.txt | tail -Z

So, for example, if you want to find :: classX, you want one line before and 5 lines after, then you would run

grep -B1 -A5 ':: classX' data.txt | tail -7

As a side note, if you want the first match you can replace tail with head. If you want to see all matches, remove the | tail -Z part.

You can add color matching also with grep --color

1

A sed solution

sed '/:: classX/h;$!d' logfile

sed matches the pattern and places the line in the hold buffer h then deletes all the lines except the last line $!d .

1

Try this. First we reverse the file line by line, then reverse each line. Then search for the reverse of 'exception threw by :: ', then print the first match. And finally reverse that.

tac logfile.txt | rev | grep -Po '\w+\s+::\s+yb\s+werht\s+noitpecxe'  | head -1 | rev

This method is particularly useful for very large files with possibly very long lines because the search is done backwards and you don't have to grep through the entire file.

  • I wanted to find the last occurrence of "exception threw by :: " then also capture couple more characters. "ClassX" is not constant and random values are expected. My intension is to find out what is the value post the :: – Tamil Oct 27 '15 at 21:59
  • Edited answer based on your comments. – gogators Oct 28 '15 at 1:20

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.