How to grep with color output

One of the powerful and widely used command in shell is grep. It searches in an input file and matches lines in which the given pattern is found. By default, all the matched patterns are printed on stdout that is usually terminal. We can also redirect the matched output to other streams such as file.

The basic usage of grep is this:

$ grep "some text" file.txt

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

The —-color parameter tells grep to color the search terms in the output, which helps them stand out when among all the other text on the line. You choose which color you want using the GREP_COLOR environment variable: export GREP_COLOR=36 gives you cyan, and export GREP_COLOR=32 gives you lime green.

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' 

Final Note

The grep command is one of the most consistently useful and powerful in the Terminal arsenal. Its premise is simple: given one or more files, print all lines in those files that match a particular regular expression pattern. To highlight the matching pattern, use the -color option. While the option position does not matter, the convention is to place options first.

Related Post