grep all .java files in a directory for a particular string
How would I search all .java files for a simple string (not a regex) in the current directory and all sub-directories on Mac OS X? I just want to print a list of file and directory names that match.
Solution 1:
And the always popular
find . -name '*.java' | xargs grep -l 'string'
EDIT (by Frank Szczerba):
If you are dealing with filenames or directories that have spaces in them, the safest way to do this is:
find . -name '*.java' -print0 | xargs -0 grep -l 'string'
There's always more than one way to do it.
Solution 2:
The traditional UNIX answer would be the one that was accepted for this question:
find . -name '*.java' | xargs grep -l 'string'
This will probably work for Java files, but spaces in filenames are a lot more common on Mac than in the traditional UNIX world. When filenames with spaces are passed through the pipeline above, xargs will interpret the individual words as different names.
What you really want is to nul-separate the names to make the boundaries unambiguous:
find . -name '*.java' -print0 | xargs -0 grep -l 'string'
The alternative is to let find run grep for you, as Mark suggests, though that approach is slower if you are searching large numbers of files (as grep is invoked once per file rather than once with the whole list of files).
Solution 3:
Use the grep that is better than grep, ack:
ack -l --java "string"
Solution 4:
This will actually use a regex if you want, just stay away from the metacharacters, or escape them, and you can search for strings.
find . -iname "*.java" -exec egrep -il "search string" {} \;
Solution 5:
grep -rl --include="*.java" simplestring *