Today I was looking over a script I wrote awhile back that searches through a large log file looking for the last entry with a certain keyword in the file and then parses out a value. I was using something like…
#The number 1255345 is completely arbitrary. tail -1255345 /some/log.log | grep searchword | tail -1 | cut -d ' ' -f7
Looking at this again I thought “There has to be a better way…” Everytime I think this, I’m inevitably right…there really is a better way. I decided what I needed was a way to grep in reverse. A quick search through grep’s man file revealed that grep has no built in way to search in reverse, though I did notice it is able to return only the first match it finds.
Most advanced users of *nix based operating systems are familiar with that cat command. It simply dumps whatever file it is given allowing you to read it, parse it, take pictures of it…whatever you want. A quick search of Google for “reverse grep” revealed that I was unaware of a very simple but extremely useful tool called tac. As the name may suggest, tac simply dumps a file in reverse order. This was exactly what I needed.
The resulting line was much cleaner and much (I imagine) more efficient.
tac /some/log.log | grep -m1 searchword | cut -d ' ' -f7
So there you go. If you need to grep in reverse, this may solve your problem in a relatively simple and elegant fashion.