Text Processing – How to Grep -v and Exclude the Next Line After Match

greptext processing

How to filter out 2 lines for each line matching the grep regex?
this is my minimal test:

SomeTestAAAA
EndTest
SomeTestABCD
EndTest
SomeTestDEFG
EndTest
SomeTestAABC
EndTest
SomeTestACDF
EndTest

And obviously I tried e.g. grep -vA 1 SomeTestAA which doesn't work.

desired output is:

SomeTestABCD
EndTest
SomeTestDEFG
EndTest
SomeTestACDF
EndTest

Best Answer

You can use grep with -P (PCRE) :

grep -P -A 1 'SomeTest(?!AA)' file.txt

(?!AA) is the zero width negative lookahead pattern ensuring that there is no AA after SomeTest.

Test :

$ grep -P -A 1 'SomeTest(?!AA)' file.txt 
SomeTestABCD
EndTest
SomeTestDEFG
EndTest
SomeTestACDF
EndTest
Related Question