Grep invert match with context

I am trying to grep a file with invert match, but also not match every line occurring right after the matching lines.

So I have the following contents in a file called testing_grep:

aaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbbb
cccccccccccccccccc
dddddddddddddddddd
llllllllllllllllll
dddddddddddddddddd
llllllllllllllllll
fffffffffffffffff
fffffffffffffffff

So I want to match all lines except the ones containing d and the next line following such a match, so I have the following grep command:

 grep -v "d" -A 1 testing_grep.txt 

However, I still get all lines being outputed while all I need is the following output:

aaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbbb
cccccccccccccccccc
fffffffffffffffff
fffffffffffffffff

Thanks for any help.

2 Answers

Try this with GNU sed:

In pattern space (current line) search (//) a line containg d. Only for those lines append the next line of input into the pattern space (N) and delete pattern space (d).

sed '/d/{N;d;}' testing_grep.txt

Output:

aaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbbb
cccccccccccccccccc
fffffffffffffffff
fffffffffffffffff

Cyrus already got you the perfect answer, but if you wana do it with grep ( which is more complicated)

you grep the lines you do not want and you put them in a file:

grep 'd' -A 1 testing_grep.txt > otherfile.txt

otherfile.txt content will be :dddddddddddddddddd llllllllllllllllll dddddddddddddddddd llllllllllllllllll

Then you use the diff command to get the difference:

diff testing_grep.txt otherfile.txt | grep '^[<>]'

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like