Tail -f - Show last X lines that match a pattern

docksteaderluke picture docksteaderluke · Nov 8, 2013 · Viewed 17.7k times · Source

I'm trying to achieve the equivalent of tail -f -n10 for a matched pattern.

At first I thought tail -f -n10 | grep PATTERN but that only returns lines that match the pattern in the last 10 lines of the file.

What I'm looking for is the last ten matches that exist in the file, not the matches in the last ten lines of the file. Is there a way to achieve this?

Please note: I specified tail -f because I would like the output to be continuous. I'm using this command to watch a log file for a specific pattern.

Answer

ryancwarren picture ryancwarren · Nov 8, 2013

grep PATTERN FILE | tail -n10; tail -f -n0 FILE | grep PATTERN;