简体   繁体   中英

Grep Next Line Only If Two Lines Above Match String Consecutively

I'm using the following command to match the following line in a file:

cat file.txt | grep -A 1 'match' > output.txt

This allows me to get the line after 'match' is found in the following file:

match
random text line 1
match
match
match
random text line 2
match
random text line 3
match
match
random text line 4
match
random text line 5
match
random text line 6
match
random text line 7
match
random text line 8
match
match
random text line 9

However, I need to return only the lines after 2 or more consecutive 'match' lines. In this case the output would be:

random text line 2
random text line 4
random text line 9

I have tried using a combination of grep -A 2 'match' | grep -A 1 'match' grep -A 2 'match' | grep -A 1 'match' but it doesn't work as it's redundant. I'm stuck on how to match only if there are two consecutive lines. I'm open to using awk or sed for matching too if it's more efficient. Any direction would be greatly appreciated.

grep stands for g/re/p ie it's for Globally finding a Regular Expression and Printing the result, that is all . That is not all that you are trying to do so therefore grep would be the wrong tool to try to use. For general purpose text manipulation the standard tool to use is awk:

$ awk '/match/{c++;next} c>1; {c=0}' file
random text line 2
random text line 4
random text line 9

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM