xinshou
xinshou

Reputation: 37

grep the last match of an occurence with the nlines after that in a file bash

may I ask how to grep the last match of an occurence with the nlines after that in a file bash? The file looks like in the following,

it is Starting 
line1
line2
ERROR
line3
line4
line5
ERROR
line6
line7
line8
WARNING
line9
ERROR
line10
line11

I want to grep the last "WARNING" with the two lines after that. The outcome should be

WARNING
line9
ERROR

I know grep -A2 "WARNING" can help all the WARNINGS with the two lines after, but how to do that for the last occurence then?

Upvotes: 1

Views: 589

Answers (1)

Timur Shtatland
Timur Shtatland

Reputation: 12347

Use tac to reverse the order of the lines in the file, grep with options -m1 for maximum 1 match, and -B2 for 2 lines preceding the match (preceding because the lines are in reverse order), followed by another tac to put the lines in the original order:

tac in_file | grep -m1 -B2 WARNING | tac

Upvotes: 2

Related Questions