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?


5 Answers 5


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"

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'

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'


Assuming you are in dir

find dir2 -name '*.c'

of course Iain's answer is also correct


When searching a set of subdirectories specified using a wildcard, do not use the -path flag as it can be slow.

tree findtest/
|-- dir_1_
|-- dir_2_
|   `-- file_2_
|-- dir_3_
|   |-- dir_3_1_
|   `-- dir_3_2_
|       `-- file_3_2_
`-- file_0_

5 directories, 3 files

(NB The current directory contains many other files and subdirectories.)

Slow using a subdirectory wildcard in '-path':

time find . -path "./findtest/dir_*_/file_*_"
0.084u 0.699s 0:17.84 4.3%      0+0k 0+0io 0pf+0w

Faster alternative:

time find ./findtest/dir_*_/ -name "file_*_"
0.000u 0.002s 0:00.00 0.0%      0+0k 0+0io 0pf+0w
  • Translating your suggestion to use find ./findtest/dir_*_/ -name "file_*_" into something using the terms that the user is using in the question, you get find dir2 -name '*.c'. This is repeated in most answers already. The rest of your answer seems to be a comment on Josh's answer (?).
    – Kusalananda
    Commented Mar 30, 2023 at 13:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .