I use the --colour option of grep a lot, but I often use less as well. How can I pipe grep results to less and still preserve the coloring. (Or is that possible?)

grep "search-string" -R * --colour | less

EDIT:

I'm looking for a direct solution or anything equivalent to this.

link|improve this question

feedback

2 Answers

up vote 22 down vote accepted

When you simply run grep --color it implies grep --color=auto which detects whether the output is a terminal and if so enables colors. However, when it detects a pipe it disables coloring. The following command:

grep --color=always -R "search string" * | less

Will always enable coloring and override the automatic detection, and you will get the color highlighting in less.

EDIT: Although using just less works for me, perhaps older version require the -R flag to handle colors, as therefromhere suggested.

link|improve this answer
9  
You need to use less -R for the colour encoding to be interpreted by less correctly – therefromhere Sep 4 '09 at 23:24
It worked for me with just less, it may be version dependent. – spatz Sep 5 '09 at 12:14
wow. I thought 'auto' only depended on the terminal type. I may be jumping the gun, but this may revolutionize the way I use linux :P – Jeremy Powell Sep 8 '09 at 14:16
Awesome. Though I too to use less -R to get less to display colours, rather than the colouring escape codes :o) – Owen Blacker Mar 6 at 15:05
1  
A (hopefully) useful addendum: I needed to exclude some matches but maintain the colouring, so I actually ended up with grep pattern file | grep -v badpattern | grep --colour=always pattern | less -R, which met my needs perfectly. (Thanks again!) – Owen Blacker Mar 6 at 15:35
feedback

You can put this in your .bashrc file:

export GREP_OPTIONS="--color=always"

or create an alias like this:

alias grepc="grep --color=always"

and you will need to use the -R option for less, as pointed out by therefromhere

link|improve this answer
3  
Warning!: GREP_OPTIONS="--color=always" may break many scripts that use grep (or (e|f)grep). – mctylr Mar 12 '10 at 19:25
Yeah, better to just alias grep. You can always get pure grep with GREP, or override the --color option manually. – asmeurer Jul 18 '11 at 22:51
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.