Monday, August 18, 2008

Grep recursively for content over a pattern of files

 

When using recursion with grep along with pattern matching of files, grep doesn’t work as expected. We intended to say, “Search the current directory recursively for all *.txt files.” What actually happens is that the shell expands *.txt to include all matching filenames (which does not include the directory archive); grep then searches each filename in the expansion, and if it’s a directory, grep does so recursively. We can’t specify to grep both a directory to search recursively and at the same time which files to consider.

$ grep -r "Janet" *.txt
   hello.txt:Dear Janet,
   lets-meet.txt:Dear Janet, sauciest of vixens
   secret-liaison.txt:Dear Janet,

The solution is to use find and xargs.

$ find . -iname "*.txt" -print0 | xargs -0 grep "Janet"
   ./archive/old-letter.txt:Dear Janet,
   ./hello.txt:Dear Janet,
   lets-meet.txt:Dear Janet, sauciest of vixens
   ./secret-liaison.txt:Dear Janet,

Source: http://www.peachpit.com/articles/article.aspx?p=441610&seqNum=3

No comments:

Post a Comment