Recessively search for a string within files using grep

To recursively search all files in a directory for ‘SearchText’ and print out matching files you can use the grep command with the ‘–files-with-matches / -l’ and ‘–recursive / -r’ flags. For example, to search the current directory (‘.’):

grep -rl "SearchText" .

Note, if you run this on a directory with lots of subdirectories (e.g., your home folder) it will take a long time to run.

You can specify to only include files matching a pattern using the ‘–include’ flag:

grep -rl --include "*py" "SearchText" .

or exclude files matching a pattern using the ‘–exclude’ flag.

grep -rl --exclude "*pyc" "SearchText" .

For more info see the man page (available online here) or the full manual available at http://www.gnu.org/software/grep/manual/.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s