The Computer Oracle

Getting colored results when using a pipe from grep to less

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping

--

Chapters
00:00 Getting Colored Results When Using A Pipe From Grep To Less
00:27 Accepted Answer Score 339
00:59 Answer 2 Score 35
01:18 Answer 3 Score 2
01:32 Answer 4 Score 16
01:53 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".