Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep last match and it's following lines

Tags:

grep

match

I've learnt how to grep lines before and after the match and to grep the last match but I haven't discovered how to grep the last match and the lines underneath it.

The scenario is a server log. I want to list a dynamic output from a command. The command is likely to be used several times in one server log. So I imagine the match would be the command and somehow grep can use -A with some other flag or variation of a tail command, to complete the outcome I'm seeking.

like image 801
srichens Avatar asked Sep 13 '13 07:09

srichens


People also ask

How do you grep all lines after a match?

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 you get 10 lines before and after grep?

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.


2 Answers

The approach I would take it to reverse the problem as it's easier to find the first match and print the context lines. Take the file:

$ cat file
foo
1
2
foo
3
4
foo
5
6

Say we want the last match of foo and the following to lines we could just reverse the file with tac, find the first match and n lines above using -Bn and stop using -m1. Then simple re-reverse the output with tac:

$ tac file | grep foo -B2 -m1 | tac
foo
5
6

Tools like tac and rev can make problems that seem difficult much easier.

like image 107
Chris Seymour Avatar answered Oct 18 '22 05:10

Chris Seymour


using awk instead:

awk '/pattern/{m=$0;l=NR}l+1==NR{n=$0}END{print m;print n}' foo.log

small test, find the last line matching /8/ and the next line of it:

kent$  seq 20|awk '/8/{m=$0;l=NR}l+1==NR{n=$0}END{print m;print n}'
18
19
like image 37
Kent Avatar answered Oct 18 '22 06:10

Kent