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

There are 3 color options available to you:


With color=always, it colors the matched string.

$ grep –color=always abc a_file.txt

Quite often, you want to page through the output:

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

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

Alternatively, use more.

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

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
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.