Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
find . -name "*.java" -exec grep "foo" {} \;

This just prints matches, no file name.

find . -name "*.java" -exec grep "foo" /dev/null {} \;

But this prints file name as well.

Why? What are the mechanics of find/grep that cause file name to print when /dev/null is inserted into the mix?

PS - yes, I know I can do "grep -H"

share|improve this question
up vote 5 down vote accepted

If you use neither the -h nor the -H option, then grep will write out the filename if more than one file is given as arguments. So if you add /dev/null as argument to grep, you will always have more than one, so the file name will always be written. But yeah, using ˛grep -H is the safest way to always have the filename written.

share|improve this answer

I would guess that grep, when searching multiple files, will output the file name in front of the matched line in order to differentiate where it found the line. Otherwise, if only one file is specified, the user already knows what file the line would be found in.

Use grep -h to turn off filenames in output, and grep -H to force them on.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .