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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With