0

I would like to use pcregrep with its --color option to highlight text that follows a particular pattern:

e.g. if file.txt contains:

bob says hi
chloe says hello

then running:

pcregrep --color '(?:says)(.*)' file.txt

prints

bob says hi
chloe says hello

but what I want is:

bob says hi
chloe says hello

Is there a way to use pcregrep and have it only highlight text that follows a particular regular expression?

cody
  • 11,045
  • 3
  • 21
  • 36
user1279887
  • 489
  • 4
  • 20

1 Answers1

1

The answer appears to be no, you cannot color only part of a match, even if it's non-capturing with (?:..) as in your example.

But if you instead use a positive lookbehind assertion, which anchors the match but is not part of it, you can achieve what you want:

pcregrep --color '(?<=says)(.*)' data

Result:

enter image description here

cody
  • 11,045
  • 3
  • 21
  • 36
  • Thanks, that works - not very intuitive. I'm actually using this to highlight the method in Soap XML logs: pcregrep --color '(?<=soap:Body><)(.*?)\s' – user1279887 Jan 26 '19 at 22:08
  • pcregrep must be buffering data, because using it conjunction with a tail -f doesn't work. – user1279887 Feb 21 '19 at 12:51