Bash Grep Subdirectories (Recursively)

by on February 17, 2007 · 2 comments· last updated at February 17, 2010

How do I recursively grep through all sub-directories and find files containing given text / string or words?

You can use the -r option to recursively grep through all sub-directories and find text. The syntax is as follows:

grep -r "text" /path/to/di

In this example, search for an IP 192.168.1.254 in through all /etc/ and all its sub-directories:

grep -r "192.168.1.254" /etc/

Search in any case:

grep -ri "letters" /home/vivek/data

Use the -l switch to display only the names of files in which the text occurs:

grep -lri "foo" /data


You should follow me on twitter here or grab rss feed to keep track of new changes.

Featured Articles:

{ 2 comments… read them below or add one }

1 Lev Elbert July 9, 2012 at 7:17 pm

Grep does allow recursive search, but only if you don’t specify the files you are looking for. For example:
grep -r ‘ActiveServer’ . works, but outputs a lot of noise (like log and binary files)

grep -r ‘ActiveServer’ *.java will tell something like:
“zsh: no matches found: *.java”

A “quick and dirty” way to solve the problem:
grep -r ‘ActiveServer’ . | grep ‘.java:’
This still might output some non-java entries.
But this doesn’t ():
grep -rl ‘ActiveServer’ . | grep ‘.java’

I usually run this command and a separate terminal tab (or window).

Reply

2 Jon OƱativia November 27, 2012 at 12:19 pm

When I want to grep over files with a specific extension in a file tree I do it combining it with “find”:
$ find . -name \*.java | xargs grep ‘ActiveServer’

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <kbd> <blockquote> <pre> <a href="" title="">

Tagged as: , , , , , , , , , , , ,

Previous Faq:

Next Faq: