I have a simple bash script. One line of my script matches a "pattern" with grep and colors the match

grep -i --color=always -- "$1"

I need to modify it, so that it only colors the match, if the line is not a comment (i.e. if it does not start with a #). In other words: I still want grep to match the commented line, but without coloring it.

Let's say I have following text file (with added line numbers)

2 bbb ccc PATTERN ddd
3 # eee PATTERN
4 fff ggg

I need my grep expression to match lines 1,2,3 but only color the lines which are not commented (1 and 2)

3 Answers 3


Using GNU grep with -P option:

$ grep PATTERN file | grep -P '^[^#]*\KPATTERN|^'
bbb ccc PATTERN ddd

\K causes all thing in the left of PATTERN don't include in matched string. This solution assumes that your grep is aliased to grep --color=auto

  • is it possible to modify the expression grep -P '^[^#]*\KPATTERN|^' to use egrep and to match two patterns, i.e. '(PATTER1|PATTERN2)' ? Commented Jun 25, 2014 at 20:25

It's not possible to have grep do conditional coloring in this manner. It can only highlight the "PATTERN" that it's matching.


just a small hack: grep -E 'PATTERN' <filename> | grep --color -E "^[^#]*|$" -

you can use this: first grep matches the lines with PATTERN and second grep colors lines that does not start with '#'.

I don't think grep --color can do conditional coloring.

  • This will color the whole line instead of PATTERN only.
    – cuonglm
    Commented May 25, 2014 at 18:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .