0

I have a file:

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

I want to match to match except This error and next three lines, I can use:

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

It gives output:

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

However, instead of removing them if I want to match them using the same command(by removing v):

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

It gives output:

This error
-this
-this
This error
-asd
-asfag
This error
-asdgsda
-asdgg

So how does pcregrep actually works?

1

Add .* to the end of your regexp.

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

I don't know if it's due to a bug or not, but it seems -v also excludes the full line after the last matched \n, but without -v it doesn't. So adding .* (i.e. not ending the regexp with \n) makes it match the last line explicitly in both cases, therefore not triggering the issue/feature.

  • I know that adding .* will work, but I am looking for reason. – Prvt_Yadav Jul 16 at 6:59
  • It's almost as the condition is: if .*<pattern>.* matches, skip the line(s) (which would make sense for a single-line invert) – muru Jul 16 at 7:12
  • @muru not looking for reason why this answer is working, looking for the reason why question which I asked is not working? – Prvt_Yadav Jul 16 at 7:37
  • @Prvt_Yadv that comment applies to both. – muru Jul 16 at 7:40

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.