How to grep -v and also exclude the next line after the match?
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
Here's a sed
solution (with -n
i.e. no auto-printing) that works with arbitrary input:
sed -n '/SomeTestAA/!p # if line doesn't match, print it
: m # label m
//{ # if line matches
$!{ # and if it's not the last line
n # empty pattern space and read in the next line
b m # branch to label m (so n is repeated until a
} # line that's read in no longer matches) but
} # nothing is printed
' infile
so with an input like
SomeTestAAXX
SomeTestAAYY
+ one line
SomeTestONE
Message body
EndTest
########
SomeTestTWO
something here
EndTest
SomeTestAABC
+ another line
SomeTestTHREE
EndTest
SomeTestAA
+ yet another line
running
sed -n -e '/SomeTestAA/!p;: m' -e '//{' -e '$!{' -e 'n;b m' -e '}' -e'}' infile
outputs
SomeTestONE
Message body
EndTest
########
SomeTestTWO
something here
EndTest
SomeTestTHREE
EndTest
that is, it removes exactly the lines that grep -A1 SomeTestAA infile
would select:
SomeTestAAXX
SomeTestAAYY
+ one line
--
SomeTestAABC
+ another line
--
SomeTestAA
+ yet another line
One option is to use p
erl c
ompatible r
egular e
xpression grep
:
pcregrep -Mv 'SomeTestAA.*\n' file
The option -M
allows pattern to match more then one line.