Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 634
Ryan Avatar asked Oct 20 '15 16:10

Ryan


People also ask

What command is used to search files for lines that match patterns?

grep With Multiword Strings The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.

How do I find a specific pattern from a file?

The grep utility searches the given input files selecting lines which match one or more patterns. The type of patterns is controlled by the options specified. By default, a pattern matches an input line if any regular expression (RE) in the pattern matches the input line without its trailing newline.

Which command is used for matching a specific pattern or expression within a file?

The grep (Global Regular Expression Print) is a unix command utility that can be used to find specific patterns described in “regular expressions”, a notation which we will learn shortly. For example, the “grep” command can be used to match all lines containing a specific pattern.

How do I find a specific file pattern in Linux?

To find files that match a specific pattern, use the -name argument. You can use filename metacharacters (such as * ), but you should either put an escape character ( \ ) in front of each of them or enclose them in quotes. All files in the current directory starting with “pro” are listed.


1 Answers

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
like image 59
carpenter Avatar answered Sep 17 '22 16:09

carpenter