Linux find/grep FAQ: How can I combine the Linux find and grep commands to search a large collection of files?
A lot of times when I need to find a file I know the text in the file that I'm looking for, but I can't remember the filename, or can't think of what directory it might be in, other than somewhere below my home directory. When this happens, and other search means like the "locate" command don't help, my favorite way of searching for text strings in files that are spread through a bunch of directories and sub-directories is this:
find . -type f -name "*.java" -exec grep -il 'foo' {} \;
Searching for text strings in a group of files
This find and grep command example can be read like this:
"Look in the current directory and all sub-directories for files ending with the characters '*.java', and when you find those files look for the string 'foo' in those files, then print the filename if the string is found."
It's a great way of merging the find and grep commands to find a text string that you know is in a file, somewhere.
Limit the list of directories to search
If you don't want to search every sub-directory and just want to search directories named "dir1", "dir2", and "dir3" you can change the find command like this:
find dir1 dir2 dir3 -type f -name "*.java" -exec grep -il 'foo' {} \;
Finally, if your know the string is in a file in the current directory there's no need to use the find command. You just use grep, like this:
grep -il 'foo' *.java
Related Unix/Linux find command examples
I've written several different Unix and Linux find command tutorials, and here are some links to a few of those articles: