Printing the last occurrence of a string and everything below it with grep

Tags: , , , , , , ,

So far the simplest way I’ve discovered to find the last occurrence of a string and print everything below it is with a combination of grep and tac (it’s cat backwards, get it?!).

Say you want to find the last instance of foo and everything that came after it in a file. You could run the following…

 tac /var/log/logfile | grep 'foo' -m 1 -B 9999 | tac

Which will flip the log file upside and pipe it through grep. Grep then finds only the first occurrence and prints everything above it (well, 9999 lines), then flips that output right side up again. Works great but I wonder if there is a simpler way to do this.

[ad]