301

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.

codeforester
  • 164
  • 1
  • 1
  • 8

5 Answers5

349

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.

drrlvn
  • 6,713
34

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

17

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)

Iazel
  • 271
2

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

not2qubit
  • 2,651
  • 4
  • 34
  • 45
0

You can run

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

with the -r flag after less, in order for this to work.