2

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)

1 aaa PATTERN
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)

4

Using GNU grep with -P option:

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

\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)' ? – Martin Vegter Jun 25 '14 at 20:25
2

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

1

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 May 25 '14 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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