Linux recursive grep

To recursively grep through directories you can use the find command to select a filenames in a directory tree and then grep to find a string within each file.

Here’s the command to find the string facebook in all javascript (*.js) files in the current directory and any sub-directories:

find . -name ‘*.js’ -exec grep ‘facebook’ -Hn ‘{}’ \;

Breaking that command down:

The first find parameter is the . that instructs it to start in the current directory. The -name parameter is followed by a filename wildcard to match, *.js in this case. Next parameter is the -exec, this is an instruction that find will execute for each file it finds – we are using grep. The grep ‘facebook’ -Hn is the grep command and its parameters – it tells grep to look for the string facebook and -Hn tells it to output the filename and line number of all matched files. Finally, the ‘{}’ \; are find parameters that instruct it to call grep for each file.

We can recursively grep for all files by omitting the -name parameter:

find . -exec grep ‘facebook’ -Hn ‘{}’ \;

We can look in another directory by changing the . for a directory name:

find /home/steve -exec grep ‘facebook’ -Hn ‘{}’ \;

Because this is a bit of a pain in the ass to remember I usually create a bash script called rgrep.sh or something like that and just call it from that.

Leave a Reply