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.
You can use the -B and -A to print lines before and after the match. Will print the 10 lines before the match, including the matching line itself.
You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.
To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file.
To also show you the lines before your matches, you can add -B to your grep. The -B 4 tells grep to also show the 4 lines before the match. Alternatively, to show the log lines that match after the keyword, use the -A parameter. In this example, it will tell grep to also show the 2 lines after the match.
grep PATTERN FILE | tail -n10; tail -f -n0 FILE | grep PATTERN;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With