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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.