16

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?

8

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'
16

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
4

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'

  • 3
    In the last command, the braces aren't needed. find dir1 dir3 -name \*.c works just fine. – KeithB Dec 15 '10 at 14:19
3

Assuming you are in dir

find dir2 -name '*.c'

of course Iain's answer is also correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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