Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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

I'm trying to have grep search inside specified files that are returned by find:

find . -type d -name 'mydir*' -exec find '{}' -name '*.java' \; | grep 'MyClass'

This doesn't work.

Meanwhile, this works.

grep 'MyClass' $(find . -type d -name 'mydir*' -exec find '{}' -name '*.java' \;)

What's the problem with my first example?

share|improve this question
up vote 6 down vote accepted

In first case you grep the list of filenames returned by find, whereas in the second case the filename list is an argument to grep, so grep will search inside the files.

Pipe is a standard input, not a named file. That's why grep behaves differently.
From man grep:

grep searches the named input FILEs (or standard input if no files are named, or if a single hyphen-minus (-) is given as file name) for lines containing a match to the given PATTERN.

share|improve this answer

Because in the first case grep tries fo find 'MyClass' in filenames and in the second one it tries to find 'MyClass' in file contents.

The first one is equal to

find . -type d -name 'mydir*' -exec find '{}' -name '*MyClass*.java' \;

while the second one is equal to

find . -type d -name 'mydir*' -exec sh -c \
"find '{}' -name '*.java' -exec grep 'MyClass' {} \;" \;
share|improve this answer
Are you saying that by using pipes i'm feeding grep with stream, so it treats it as a text to search in rather than file names? – user7477 Jul 12 '12 at 14:58
@gasan Yes, if you pipe data into grep it searches it as text, it doesn't treat it as filenames. I think you're looking to stick xargs in the pipe – Michael Mrozek Jul 12 '12 at 15:00

I think your find command should be:

find . -type f -path 'mydir*.java'| xargs grep -H 'MyClass'

Which finds files in mydir with .java extension and containing MyClass. -H instructs grep to output filename in front of result.

share|improve this answer

Your Answer


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