Linux / UNIX Recursively Search All Files For A String

by Vivek Gite on July 4, 2007 · 5 comments

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

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"

Featured Articles:

Share this with other sys admins!
Facebook it - Tweet it - Print it -

{ 5 comments… read them below or add one }

1 rjbcollege May 27, 2010

That is fantastic, a command that says it does exactly what I’m looking for.

Unfortunately, when I copy and paste the example to recursivle search for files containing a string:
find . -type f -exec grep -l “word” {} +

in to my linux session I get a set of error message lines which all say this:

find: grep: Argument list too long

To fix this, simply add the following to hide any such error messages by oplacing them in the trash:

find . -type f -exec grep -l “word” {} + 2>>/dev/null

Reply

2 Pete Shore July 25, 2010

Perfect, had to search a joomla install for all occurrences of a string, used grep as i remember if from my uni days, thanks for the post.

Pete

Reply

3 lanh May 14, 2011

Thank you this was very useful for debugging!

Reply

4 Radhakrishnan July 12, 2011

This tutorial is very useful .

Reply

5 Fernando Lopez Jr. October 2, 2011

it won’t work if you are trying to search for:

grep -r “test!!!” .

you need to use the single quotations. like:

grep -r ‘test!!!’ .

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 4 + 4 ?
Please leave these two fields as-is:
Solve the simple math so we know that you are a human and not a bot.




Previous post:

Next post: