Grep double pipe with less, preserving color

This one was a little troublesome to figure out

Basically I want to search for one word, get the 10 sentences following it, pipe into a grep for another word, and then show the result a screenful at a time


grep -R -i -n -A 10 -B 10 "$1" * --color=always | grep -R -i -n -A 2 -B 2 "$2" * --color=always | less -R


The color=always is unnecessary for the first pipe.


Alternately a slightly different approach is to search for both words (OR condition)


egrep -w 'profilelink|template name' * --color=always | less -R


where profilelink and “template name” are the two strings I want to search for.

The results differ. However I prefer the first approach because I want to search for the string template name, get the 10 sentences following it and see whether this context contains the next work I wish to search for.


Of course when you use the first approach, only the second string is color highlighted. You can pipe that into the second method and get color highlighting for both words. In effect this approach searches for files containing both strings, and highlights both words in the result.

This is what I’m talking about:

dblsearch ‘template name’ ‘profilelink’ | egrep -w ‘profilelink|template name’ –color=always | less -R

where dblsearch is the following bash script:

grep -R -i -n -A 10 -B 10 "$1" * --color=always | grep -R -i -n -A 2 -B 2 "$2" * --color=always | less -R

So the final bash script is this:

grep -R -i -n -A 12 -B 12 "$1" * --color=always | grep -R -i -n -A 12 -B 12 "$2" * --color=always | less -R | egrep -w -A 12 -B 12 "$stringA" --color=always | less -R

To run it:

dblsearch 'string 1' 'string 2'


Alternately, if you always want color on in your grep results, set the GREP_OPTIONS variable in .bashrc:

export GREP_OPTIONS='--color=always'

So finally, it becomes:

grep -in [searchterm] [filename] | less -R

You are reading this post on Joel G Mathew’s tech blog. Joel's personal blog is the Eyrie, hosted here.