Unix/Linux find command FAQ: How can I write one Unix find
command to find multiple filenames (or filename patterns)? For example, I want to find all the files beneath the current directory that end with the file extensions ".class" and ".sh".
You can use the Linux find
command to find multiple filename patterns at one time, but for most of us the syntax isn't very common. In short, the solution is to use the find
command's "or" option, with a little shell escape magic. Let's take a look at several examples.
Linux find multiple filenames command - two filename patterns
Here's a Linux find
command that shows how to find multiple filenames at one time, in this case all files beneath the current directory ending with the filename extensions ".class" and ".sh":
find . -type f \( -name "*.class" -o -name "*.sh" \)
If you’re familiar with common Linux find commands, the only magic here is (a) using the "-o" option to say "or", and (b) escaping the parentheses with the backslash character.
I've tested this 'find multiple' command on several Unix systems, and it should work on all systems that support the Bash shell, including vanilla Unix, Linux, BSD, freeBSD, AIX, Solaris, and Cygwin.
Linux find multiple filenames command: finding three filename extensions
To help you see how to expand this from finding two filename patterns to finding even more filename patterns with one find
command, here's an example of how to search for three different files extensions with one find
command:
find . -type f \( -name "*cache" -o -name "*xml" -o -name "*html" \)
I just tested this on a MacOS system, and it worked fine.
FWIW, note that in these examples I keep using ".", which means "look in the current directory, and anywhere beneath here", and "-f", which means "only look for files, not directories". Those find command options aren't always necessary, so I thought I should mention them.
Linux find multiple filename extensions - Summary
I hope these examples of how to use the Linux find
command to find multiple filenames (filename extensions) with one command has been helpful. If you're looking for other uses of the find
command, check out my Linux find command examples page. I also have articles on searching Linux text files with find and grep, and an article on how to grep multiple patterns, which uses a similar approach to this article to search for multiple text patterns.