Last grep match, and the following lines

I found out how grep lines were before and after the match, and before grep last match, but I did not find how grep last match and lines below it.

A script is a server log. I want to list the dynamic output from a command. The command is likely to be used several times on the same server. So I assume that a match would be a command, and somehow grep might use -A with some other flag or variation of the tail command to complete the outcome I'm looking for.

+6
source share
2 answers

An approach I would like to take to undo the problem, since it is 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 

Let's say we want the last match foo and the next one in lines we can just cancel the file with tac , find the first match and n lines above using -Bn and stop using -m1 . Then just flip the output with tac:

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

Tools like tac and rev can create problems that seem complicated a lot easier.

+10
source

using awk:

 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 following line:

 kent$ seq 20|awk '/8/{m=$0;l=NR}l+1==NR{n=$0}END{print m;print n}' 18 19 
+1
source

Source: https://habr.com/ru/post/953754/


All Articles