Anyone that uses the unix command line on a regular basis will probably also use
grep a lot to search input files for a certain string. I use it many times each day, but somehow didn’t bother to improve my “grep fu”.
Since I rather match too much than too little, I usually give
grep a slightly too generic search string and have it look in more files than really is necessary. Then I will patiently step through the results to get to the file I’m looking for. (You’ll probably already see several parts where this can be improved.)
Pipes, pipes, pipes
To drill down into the results of a
grep on the text
FIRST_STRING, I usually piped it to another
grep command and then searched for the text
grep FIRST_STRING /path/to/files/ -R | grep SECOND_STRING
And if you needed to eliminate even more matches from the result set, you could add more pipes.
grep has the option to search for patterns that contain a regular expression. (It’s the re in grep.) Why not use that feature to get rid of the pipe structure? Then we have the following single command:
grep FIRST_STRING.*SECOND_STRING /path/to/files/ -R
This will only match patterns where
SECOND_STRING will follow
FIRST_STRING, not the other way around. This is how I would use the pipe-method anyway, so for me that’s no big deal.
And of course, this also works with
ack FIRST_STRING.*SECOND_STRING /path/to/files/