Getting colored results when using a pipe from grep to less

Solution 1:

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.

Solution 2:

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

Solution 3:

In case like this, I prefer to actually create small sh files and put them on /usr/local/bin.
I usually use grep in the recursive way on the pwd, so thats my personal script:

#!/bin/sh
grep --color=always -r "$@" . | less -R

And then I've just copied it as /usr/local/bin/g (yes, I use it a lot)

Solution 4:

Don't alias "grep", better to alias "less" which is never used by shells. In your .bashrc just put: alias less="less -r".