Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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)

share|improve this question
up vote 4 down vote accepted

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

share|improve this answer
is it possible to modify the expression grep -P '^[^#]*\KPATTERN|^' to use egrep and to match two patterns, i.e. '(PATTER1|PATTERN2)' ? – Martin Vegter Jun 25 '14 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.

share|improve this answer

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.

share|improve this answer
This will color the whole line instead of PATTERN only. – cuonglm May 25 '14 at 18:33

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.