How can I `find` files matching pattern within a directory matching another pattern from the command line?

Ryan picture Ryan · Oct 20, 2015 · Viewed 17.4k times · Source

Say I want to find all files in /Path named file_name*. Easy:

$ find /Path -name "file_name*"
/Path/foo1/file_name1.txt
/Path/foo2/file_name2.txt
/Path/bar3/file_name3.txt
/Path/bar4/file_name4.txt

What if I only want to search subdirectories like bar?

I could pipe the results, but this is highly inefficient.

$ find /Path -name "file_name*" | grep "bar"
/Path/bar3/file_name3.txt
/Path/bar4/file_name4.txt

Is there a way to get them all in the find and to skip searching directories not matching bar?

Note: If I search /Path/bar3 specifically results come back instantly. But if I search just /Path and then grep for bar it takes 30-60 seconds. This is why piping to grep isn't acceptable.

Answer

carpenter picture carpenter · Oct 20, 2015

You use a wildcard in the -name parameter but you can also use it in the path parameter.

find /Path/bar* -name "file_name*"

I created the following test directory:

./Path
|-- bar
    `-- file_name123.txt
|-- bar1
    `-- file_name234.txt
|-- bar2
    `-- file_name345.txt
|-- foo
    `-- file_name456.txt

The above command gives:

Path/bar/file_name123.txt
Path/bar1/file_name234.txt
Path/bar2/file_name345.txt