grep with color output [linux]

grep is capable of color-highlighting the matched string in its output. But, by default, that option is turned off.

$ grep abc a_file.txt
abcdef

There are 3 color options available to you:

–color=auto
–color=always
–color=never

With color=always, it colors the matched string.

$ grep –color=always abc a_file.txt
abcdef

Quite often, you want to page through the output:

$ grep –color=always abc a_file.txt |less
ESC[01;31mabcESC[00mdef
(END)

The problem is that less does not understand those control characters, by default. You need to use the -R parameter.

$ grep –color=always abc a_file.txt |less -R
abcdef

Alternatively, use more.

$ grep –color=always abc a_file.txt | more
abcdef

Another problematic scenario is when you want to save the grep output to a file. The output file will contain those control characters.

$ grep –color=always abc a_file.txt > myoutput.txt
$ less myoutput.txt
ESC[01;31mabcESC[00mdef
myoutput.txt (END)

With color=auto, it displays color in the output unless the output is piped to a command, or redirected to a file.

Lastly, you can specify the color parameter in a grep-specific environment variable. Then, you don’t have to enter it in the command line.

$ export GREP_OPTIONS=’–color=always’

So, go ahead, and add color to your Linux world.