Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using find to locate files that match one of multiple patterns

Tags:

find

shell

I was trying to get a list of all python and html files in a directory with the command find Documents -name "*.{py,html}".

Then along came the man page:

Braces within the pattern (‘{}’) are not considered to be special (that is, find . -name 'foo{1,2}' matches a file named foo{1,2}, not the files foo1 and foo2.

As this is part of a pipe-chain, I'd like to be able to specify which extensions it matches at runtime (no hardcoding). If find just can't do it, a perl one-liner (or similar) would be fine.

Edit: The answer I eventually came up with include all sorts of crap, and is a bit long as well, so I posted it as an answer to the original itch I was trying to scratch. Feel free to hack that up if you have better solutions.

like image 790
Xiong Chiamiov Avatar asked Jul 15 '09 20:07

Xiong Chiamiov


People also ask

Which command will search the contents of files for a pattern?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in.

How do I search for a string in multiple files?

Use ls and sls to Search a String in Multiple Files and Return the Name of Files in PowerShell. The ls command is popular to list files and directories in Unix and Unix-like operating systems. The ls command is also available in the PowerShell and functions similarly.

What does find command do in Linux?

The Linux find command is one of the most important and frequently used command command-line utility in Unix-like operating systems. The find command is used to search and locate the list of files and directories based on conditions you specify for files that match the arguments.


2 Answers

Use -o, which means "or":

find Documents \( -name "*.py" -o -name "*.html" \) 

You'd need to build that command line programmatically, which isn't that easy.

Are you using bash (or Cygwin on Windows)? If you are, you should be able to do this:

ls **/*.py **/*.html 

which might be easier to build programmatically.

like image 194
RichieHindle Avatar answered Sep 18 '22 19:09

RichieHindle


Some editions of find, mostly on linux systems, possibly on others aswell support -regex and -regextype options, which finds files with names matching the regex.

for example

find . -regextype posix-egrep -regex ".*\.(py|html)$"  

should do the trick in the above example. However this is not a standard POSIX find function and is implementation dependent.

like image 20
intelekt Avatar answered Sep 19 '22 19:09

intelekt