Search This Blog

Loading...

Tuesday, October 30, 2007

grep with color output

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.

P.S. Additional grep articles from this blog:

StumbleUpon Toolbar

5 comments:

ychaouche said...

less -R did not work for me. The output is not colored.

mtrob said...

My grep doesn't seem to understand --color, I get the help screen and it is not in the man page either.

JP said...

thanks, great guide. Not sure why it's not enabled by default, it's so handy.

I only learned it was possible after executing grep commands on my web host, which does happen to have it set to "always" by default.

JP said...

thanks, great guide. Not sure why it's not enabled by default, it's so handy.

I only learned it was possible after executing grep commands on my web host, which does happen to have it set to "always" by default.

Anonymous said...

Yeah, thanks