- 20 Sep 2008 -

I struggled for a long while to get the unix “grep” program to do a true multi word search.  However, grep merely searches within lines, so only files that had all words in the phrase on the same line would be returned.  I wanted to know which files in the current folder contained the words “Reuben”, “Onida” and “Cornelius” anywhere (and in any order) within them.

The solution turned out to be to grep three times and pipe each result into the next:

grep -l Reuben * | xargs grep -l Onida | xargs grep -l Cornelius

The first grep -l Reuben * returns all file names that contain the word “Reuben”.  Piping that to xargs makes the second argument essentially grep -l Onida file1 file2 file3 file4 etc.  This chaining can go on for as many search phrases as you have.  The final output is a list of files that contain every word in your search phrase.

This is in the babble category tagged as , ,

Add a comment »