Home » Questions » Computers [ Ask a new question ]

grep all .java files in a directory for a particular string

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.

Asked by: Guest | Views: 80
Total answers/comments: 5
Guest [Entry]

"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."
Guest [Entry]

"Use the grep that is better than grep, ack:

ack -l --java ""string"""
Guest [Entry]

"Since this is an OSX question, here is a more OSX specific answer.
Skip find and use Spotlight from the command line. Much more powerful!

Most people don’t know you can do Spotlight searches from the command
line. Why remember all the arcane find and grep options and what not
when you can let Spotlight do the work for you. The command line
interface to Spotlight is called mdfind. It has all the same power as
the GUI Spotlight search and more because it is scriptable at the
command line!"
Guest [Entry]

"Give this a go:

grep -rl ""string"" */*java"
Guest [Entry]

You could also use a GUI program like TextWrangler to do a more intuitive search where the options are in the interface.