Grep – Getting Colored Results When Using a Pipe from Grep to Less

colorsgreplesspipe

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.

Best Answer

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.

Related Question