Getting colored results when using a pipe from grep to less
Mia Lopez
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.
35 Answers
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" * | lessWill 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.
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
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 -RAnd then I've just copied it as /usr/local/bin/g (yes, I use it a lot)
Don't alias "grep", better to alias "less" which is never used by shells. In your .bashrc just put: alias less="less -r".
I need to run
grep --color=always -R "search string" * | less - rwith the -r flag after less, in order this to run.
2