Search code examples
pcrepcregrep

Using pcregrep with --color option - only highlight non captured expression?


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?


Solution

  • 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