Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

match

tail

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.

like image 430
docksteaderluke Avatar asked Nov 08 '13 18:11

docksteaderluke


People also ask

Which of the following command will print 10 lines before and after a pattern error match?

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.

How do I print 10 lines after grep?

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.

How do I make my cat last 10 lines of a file?

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.

How do you grep a line before a match?

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.


1 Answers

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

like image 90
ryancwarren Avatar answered Oct 06 '22 23:10

ryancwarren