Colorized grep -- viewing the entire file with highlighted matches


Question

I find grep's --color=always flag to be tremendously useful. However, grep only prints lines with matches (unless you ask for context lines). Given that each line it prints has a match, the highlighting doesn't add as much capability as it could.

I'd really like to cat a file and see the entire file with the pattern matches highlighted.

Is there some way I can tell grep to print every line being read regardless of whether there's a match? I know I could write a script to run grep on every line of a file, but I was curious whether this was possible with standard grep.

1
467
9/19/2014 8:13:40 AM

Accepted Answer

Here are some ways to do it:

grep --color -E 'pattern|$' file
grep --color 'pattern\|$' file
egrep --color 'pattern|$' file
746
9/19/2017 6:53:45 AM

Here's something along the same lines. Chances are, you'll be using less anyway, so try this:

less -p pattern file

It will highlight the pattern and jump to the first occurrence of it in the file.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon