Take the 2-minute tour ×
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.

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
add comment

3 Answers 3

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
add comment

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
5  
@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
add comment

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
add comment

Your Answer

 
discard

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