Linux grep FAQ: How can I perform a recursive search with the Linux grep command?
For years I've always used variations of the following Linux find and grep commands to recursively search subdirectories for files that match my grep pattern:
find . -type f -exec grep -l 'alvin' {} \;
This command can be read as, "Search all files in all subdirectories of the current directory for the string 'alvin', and print the filenames that contain this pattern." It's an extremely powerful approach for recursively searching files in all subdirectories that match the pattern I specify.
However, I was just reminded that a much easier way to perform the same recursive search is with the -r flag of the grep command:
grep -rl alvin .
As you can see, this is a much shorter command, and it performs the same recursive search as the longer command.
If you haven't used commands like these before, to demonstrate the results of this search, in a PHP project directory I'm working in right now, this command returns a list of files like this:
./index.tpl ./js/jquery-1.6.2.min.js ./webservice/ws_get_table_names.php
Your recursive grep searches don't have to be limited to just the current directory. This next example shows how to recursively search two unrelated directories for the case-insensitive string "alvin":
grep -ril alvin /home/cato /htdocs/zenf
In this example, the search is made case-insensitive by adding the -i flag to the grep command.
You can also perform recursive searches with the egrep command, which lets you search for multiple patterns at one time. Since I tend to mark my code with my initials ("aja") or my name ("alvin"), this recursive egrep command shows how to search for those two patterns, again in a case-insensitive manner:
egrep -ril 'aja|alvin' .
Note that in this case, quotes are required around my search pattern.
A few notes about the "grep -r" command:
Here is the section of the Linux grep man page that discusses the -r flag:
-R, -r, --recursive Read all files under each directory, recursively; this is equivalent to the -d recurse option. --include=PATTERN Recurse in directories only searching file matching PATTERN. --exclude=PATTERN Recurse in directories skip file matching PATTERN.
As you've seen, the grep -r command makes it easy to recursively search directories for all files that match the search pattern you specify, and the syntax is much shorter than the equivalent find/grep command.
For more information on the find command, see my Linux find command examples, and for more information on the grep command, see my Linux grep command examples.
Post new comment