The Computer Oracle

Getting colored results when using a pipe from grep to less

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC O Beethoven - Piano Sonata No 3 in C

--

Chapters
00:00 Question
00:33 Accepted answer (Score 329)
01:15 Answer 2 (Score 34)
01:40 Answer 3 (Score 16)
02:12 Answer 4 (Score 2)
02:30 Thank you

--

Full question
https://superuser.com/questions/36022/ge...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#colors #grep #pipe #less

#avk47



ACCEPTED ANSWER

Score 339


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.




ANSWER 2

Score 35


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




ANSWER 3

Score 16


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)




ANSWER 4

Score 2


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