4

So I'm trying to use grep with both -v argument and -A argument.

So my file has text like:

This error
-this
-this
-that
[text I want]
This error
-asd
-asfag
-adsfhs
[text I want]
[text I want]
This error
-asdgsda
-asdgg
-gasdg

After a tail, I found out that this log file is filled with the same This error followed by 3 lines construct, and I can easily find them by using grep -A3 'This error', this shows me the error and the 3 lines after it.

But I want to see everything OTHER than that, hence the -v argument, but it doesn't work. When I do grep -v -A3 'This error' it returns the whole file, like grep didn't even work at all.

What is the problem here?

  • 2
    "The problem" is, that grep checks for every line whether it contains "This error" or not. And if not, it prints out the the next 3 lines whatever they contains (But grep avoid printing the same line multiple times). So it also output lines you don't want to see. – finswimmer Jul 16 at 4:59
1

If you can use sed instead of grep, it provides a nice solution:

sed -e '/This error/,+3d' myfile

This removes the line containing the string This error and the following three lines, but outputs everything else. This sed command requires GNU sed (the +3 address is an extension).

0

You can use pcregrep:

pcregrep -vM  'This error\n.*\n.*\n.*' file

It will give output:

[text I want]
[text I want]
[text I want] 

Reference https://stackoverflow.com/q/2686147/9235408

0

As finswimmer pointed out in comments, your grep -v command would output the three lines after each line that does not match the text This error. This is not what you want.

Using standard sed:

sed '/This error/{ N;N;N; d; }' file

This looks for the text This error in the file, and when this is found it reads the next three lines as well, and deletes all four lines. All other lines are outputted.

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.