Problem :
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.
Solution :
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
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
.
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+ybs+werhts+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.