0

Is it possible to have grep search for multiple expressions, but only colour a specific one of them?

Example of what I'm after:

cat file | grep -e foo --colour -e bar 

Output (where bold represents coloured):

foo baz

bar baz

qux foo

foo bar

2 Answers 2

1

PCRE can be abused so that there is a match but nothing matched that would be highlighted:

grep -P 'foo.*\K$|bar' input
1
  • Or grep -P '(?=foo)|bar' (which would also work with older versions of PCRE). Commented Nov 17, 2017 at 16:13
0

A solution (though not particularly elegant) is to use multiple grep queries.

cat file | grep -e foo -e bar | grep -9999 --colour -e bar

Note: The -9999 flag is a hack to get grep to output a lot of lines from stdin. It is possible to increase the value if it is required.

1
  • 1
    Or <file grep -e foo -e bar | grep --colour -e '^' -e bar Commented Nov 17, 2017 at 16:14

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.