1

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.

3

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
0

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.