DomainsFeatured DomainsFeatured - 2 months ago 12
Linux Question

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


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


I have tried using a combination of
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.

Answer

grep stands for g/re/p i.e. 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{print;c=0}' file
random text line 2
random text line 4