Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.
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

2 Answers 2

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.