Highlight text similar to grep, but don't filter out text [duplicate] – Dev

The best answers to the question “Highlight text similar to grep, but don't filter out text [duplicate]” in the category Dev.


When using grep, it will highlight any text in a line with a match to your regular expression.

What if I want this behaviour, but have grep print out all lines as well? I came up empty after a quick look through the grep man page.


You can make sure that all lines match but there is nothing to highlight on irrelevant matches

egrep --color 'apple|' test.txt 


  • egrep may be spelled also grep -E
  • --color is usually default in most distributions
  • some variants of grep will “optimize” the empty match, so you might want to use “apple|$” instead (see: https://stackoverflow.com/a/13979036/939457)


Use ack. Checkout its --passthru option here: ack. It has the added benefit of allowing full perl regular expressions.

$ ack --passthru 'pattern1' file_name

$ command_here | ack --passthru 'pattern1'

You can also do it using grep like this:

$ grep --color -E '^|pattern1|pattern2' file_name

$ command_here | grep --color -E '^|pattern1|pattern2'

This will match all lines and highlight the patterns. The ^ matches every start of line, but won’t get printed/highlighted since it’s not a character.

(Note that most of the setups will use –color by default. You may not need that flag).


You can use my highlight script from https://github.com/kepkin/dev-shell-essentials

It’s better than grep cause you can highlight each match with it’s own color.

$ command_here | highlight green "input" | highlight red "output"

enter image description here



This works with OS X Mountain Lion’s grep:

grep --color -E 'pattern1|pattern2|$'

This is better than '^|pattern1|pattern2' because the ^ part of the alternation matches at the beginning of the line whereas the $ matches at the end of the line. Some regular expression engines won’t highlight pattern1 or pattern2 because ^ already matched and the engine is eager.

Something similar happens for 'pattern1|pattern2|' because the regex engine notices the empty alternation at the end of the pattern string matches the beginning of the subject string.

[1]: http://www.regular-expressions.info/engine.html


I ended up using perl:

perl -pe 's:pattern:\033[31;1m$&\033[30;0m:g'

This assumes you have an ANSI-compatible terminal.


If you’re stuck with a strange grep, this might work:

grep -E --color=always -A500 -B500 'pattern1|pattern2' | grep -v '^--'

Adjust the numbers to get all the lines you want.

The second grep just removes extraneous -- lines inserted by the BSD-style grep on Mac OS X Mountain Lion, even when the context of consecutive matches overlap.

I thought GNU grep omitted the -- lines when context overlaps, but it’s been awhile so maybe I remember wrong.