Thursday, June 7, 2012

Recursive Grep


How do I grep (i.e. search for a string) recursively through subdirectories on UNIX?

   find . | xargs grep some_pattern
This searches through all files starting from the current directory down. Note that this includes non-text files.
   find . -name "*.txt" | xargs grep some_pattern
This will restrict your search to certain file names or file types.


Grep command: Recursively Search All Files For A String
cd /path/to/dir
grep -r "word" .

grep -r "string" .
Ignore case distinctions:
grep -ri "word" .
To display print only the filenames with GNU grep, enter:
grep -r -l "foo" .
You can also specify directory name:
grep -r -l "foo" /path/to/dir/*.c

find command: Recursively Search All Files For A String

find command is recommend because of speed and ability to deal with filenames that contain spaces.
cd /path/to/dir
find . -type f -exec grep -l "word" {} +
find . -type f -exec grep -l "seting" {} +
find . -type f -exec grep -l "foo" {} +
Older UNIX version should use xargs to speed up things:
find /path/to/dir -type f | xargs grep -l "foo"
It is good idea to pass -print0 option to find command that it can deal with filenames that contain spaces or other metacharacters:
find /path/to/dir -type f -print0 | xargs -0 grep -l "foo
I find myself needing this more and more often lately, so I figured this is as good a place as any to keep track of it. Here's how to recursively search for files containing a particular string or regular expression. This should work on most Linux or UNIX systems, depending on your configuration.
    find -type f -name "*" | xargs grep 'word, phrase, or regular expression'
Summary for the curious:
  • find returns the names of one or more files, but not their contents.
  • -type f tells find to only look at files, not directories.
  • -name "*" tells find to examine everything. You can replace this with "*.js" to only search JavaScript files, for example.
  • | "pipes" the output of the command on the left to the input of the command on the right.
  • xargs creates and executes a command based on the arguments you pass to it.
  • grep searches the contents of files and returns each line that is a match.
  • '...' is a regular expression (or just a word, if you prefer) that indicates what you are searching for.




No comments:

Post a Comment