Linux file search - Combine find and grep to search 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 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' {} \;

This command can be read as "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.

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:

Post new comment

The content of this field is kept private and will not be shown publicly.