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
Joel G Mathew, known in tech circles by the pseudonym Droidzone, is an opensource and programming enthusiast.
He is a full stack developer, whose favorite languages are currently Python and Vue.js. He is also fluent in Javascript, Flutter/Dart, Perl, PHP, SQL, C and bash shell scripting. He loves Linux, and can often be found tinkering with linux kernel code, and source code for GNU applications. He used to be an active developer on XDA forums, and his tinkered ROMS used to be very popular in the early 2000s.
His favorite pastime is grappling with GNU compilers, discovering newer Linux secrets, writing scripts, hacking roms, and programs (nothing illegal), reading, blogging. and testing out the latest gadgets.
When away from the tech world, Dr Joel G. Mathew is a practising ENT Surgeon, busy with surgeries and clinical practise.