Home » Questions » Computers [ Ask a new question ]

Getting colored results when using a pipe from grep to less

Getting colored results when using a pipe from grep to less

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?)

Asked by: Guest | Views: 29
Total answers/comments: 2
Guest [Entry]

"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."
Guest [Entry]

"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)"