Linux / UNIX Recursively Search All Files For A String

How do I recursively search all text files for a string such as foo under UNIX / Linux / *BSD / Mac OS X shell prompt?

You can use grep command or find command as follows.

grep command: Recursively Search All Files For A String

The syntax is:
cd /path/to/dir
grep -r "word" .

grep -r "string" .
To 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" {} +
find /search/dir/ -type f -name "*.c" -print0 | xargs -I {} -0 grep "foo" "{}"
 
## Search /etc/ directory for 'nameserver' word in all *.conf files ##
find /etc/ -type f -name "*.conf" -print0 | xargs -I {} -0 grep "nameserver" "{}"

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" {} +
find /search/dir/ -type f -name "*.c" -print0 | xargs -I {} -0 grep "foo" "{}" ## Search /etc/ directory for ‘nameserver’ word in all *.conf files ##
find /etc/ -type f -name "*.conf" -print0 | xargs -I {} -0 grep "nameserver" "{}"

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"
OR use the following OSX/BSD/find or GNU/find example:

find /path/to/dir/ -type f -name "file-pattern" -print0 | xargs -I {}  -0 grep -l "search-term" "{}"
 
## OR ##
find /mycool/project/ -type f -name "*.py" -print0 | xargs -I {}  -0 grep -H --color "methodNameHere" "{}"
 
## OR search all files in /etc/ dir for 'nameserver' word ##
find /etc/ -iname "*" -type f -print0  |  xargs -0 grep -H "nameserver"

find /path/to/dir/ -type f -name "file-pattern" -print0 | xargs -I {} -0 grep -l "search-term" "{}" ## OR ##
find /mycool/project/ -type f -name "*.py" -print0 | xargs -I {} -0 grep -H –color "methodNameHere" "{}" ## OR search all files in /etc/ dir for ‘nameserver’ word ##
find /etc/ -iname "*" -type f -print0 | xargs -0 grep -H "nameserver"

Sample outputs from the last command:

Fig.01: Unix and Linux: How to Grep Recursively?

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.