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.

Let's say I have a directory dir with three subdirectories dir1 .. dir3. And inside I have many files and other subdirectories.

I'd like to search for a file inside, say with a *.c ending, but I'd only like to search in subdirectory "dir/dir2" and all its subdirectories. How can I formulate that?

Assuming I'm in dir/ I have:

find . -name "*.c"

to search in all directories.

How do I restrict to only dir2?

share|improve this question
    
man find answers your question in no time. –  alex Dec 15 '10 at 13:36
1  
@alex So do we :) –  Michael Mrozek Dec 15 '10 at 15:03
    
@Michael: yep, but man apparently got much more spare time than we all do combined :) –  alex Dec 15 '10 at 18:58
    
@alex but we get rep for answering, man doesn't :-) –  Josh Dec 16 '10 at 14:11

4 Answers 4

up vote 4 down vote accepted

Find will accept any valid path so

find ./dir2 -name '*.c'

should do the trick

If the dir directory is /home/user/dir you could give find the full path

find /home/user/dir/dir2 -name '*.c'
share|improve this answer

Assuming you are in dir

find dir2 -name '*.c'

of course Iain's answer is also correct

share|improve this answer

You can do find dir2 -name '*.c'

You could also do (cd dir2; find -name '*.c')

If you wanted to look at dir1 and dir3 but not dir2, you could do find {dir1,dir3} -name '*.c'

share|improve this answer
2  
In the last command, the braces aren't needed. find dir1 dir3 -name \*.c works just fine. –  KeithB Dec 15 '10 at 14:19

You could also use the -path parameter of find in place of -name:

find . -path "dir2/*.c"

This could allow you to find files in dir2 even if dir2 were not a direct subdirectory, E.G:

# find . -path "*/dir2/*.c"
./dir_a/dir2/file.c
./dir_b/dir2/file.c
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.