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.
Steve says
awk ‘/match/ { print $7 }’ file | tail -1
clifgriffin says
This would work, but it seems a bit inefficient. It has to search the whole file, return matches, and take the last match. It is a shortcut to the 7th field…but I’m not sure the iteration from the top of the file is efficient. Especially if you have a large log file (like in my case).
The method I listed starts at the end of the file…a much shorter distance to the information in question. I’m also assuming that cut is about as efficient as awk for this type of search, but I’ll let smarter people than I sort that out.
mudd1 says
Thanks a lot! I had a line very much like the first one you posted and that hunch that there has to be a better way. When I typed “reverse grep” into Google, I came to this post 🙂 Sad thing is, I actually once knew about tac but forgot about it until you mentioned it here.
mudd1 says
Thanks a lot! I had a line very much like the first one you posted and that hunch that there has to be a better way. When I typed “reverse grep” into Google, I came to this post 🙂 Sad thing is, I actually once knew about tac but forgot about it until you mentioned it here.
RicS says
Thanks! This goes in my text file of useful Linux command line tricks.
RicS says
Thanks! This goes in my text file of useful Linux command line tricks.