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?

Prvt_Yadav
  • 5,732
  • 7
  • 32
  • 48
  • 3
    Possible duplicate of [pcregrep excluding multiple lines regexp eats one more line than needed](https://unix.stackexchange.com/questions/383023/pcregrep-excluding-multiple-lines-regexp-eats-one-more-line-than-needed) – muru Jul 16 '19 at 05:11
  • @muru in that question replacing `\s` with 'space' solves the problem. – Prvt_Yadav Jul 16 '19 at 05:13
  • Actually [it didn't](https://unix.stackexchange.com/questions/383023/pcregrep-excluding-multiple-lines-regexp-eats-one-more-line-than-needed#comment681032_383042): "the general answer is not quite true: my pcregrep 8.39 still eats mango with `pcregrep -M -v 'banana.*\n( +.*\n)*'`" – muru Jul 16 '19 at 05:30
  • https://www.pcre.org/original/doc/html/pcregrep.html ? – K7AAY Jul 16 '19 at 18:54

1 Answers1

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.

Jonas Berlin
  • 1,099
  • 9
  • 11