I have inherited a vast media archive without a unifying organizational scheme. Its contents date back at least 10 years. I have been asked to find a needle in this hay stack, and I have some guesses as to that needle's name. But I don't know its name for certain. I want to use a single find command in the Terminal to search for alternate names. And I want to include a second set: possible file extensions. In pseudocode, here's what I mean: find [in a given directory] [files and folders whose name matches (*guess1* OR *guess2*) AND whose name matches (*.extension1 OR *.extension2)]. How should I express this in the Terminal?


You can do this using ls and grep with regular expressions

ls | grep -E "(guess1|guess2)(\.extension1|\.extension2)"

Or if you need to recursively look into folders:

ls -R | grep -E "(guess1|guess2)(\.extension1|\.extension2)"
  • 2
    Obligatory note: there are downsides to parsing ls.
    – grg
    May 1 '14 at 17:07
  • I second the admonition from @grgarside that parsing the output of ls is a poor approach to choose in general, even though it may happen to do the job for you. May 1 '14 at 23:28

Use the command

find /dir/to/search \( -iname '*guess1*' -o -iname '*guess2*' \) \
                    \( -iname '*.extension1' -o -iname '*.extension2' \)

find works recursively. Use -maxdepth 1 to make it non-recursive.

-iname does a case-insensitive filename match.

Arguments are implicitly joined by AND, but you can use -o to make it OR. Parentheses have to be escaped with a backslash to protect them from the shell.

(It could be written all on one line; here I've broken the lines using \return for readability.)


If the volume is indexed by Spotlight, then use mdfind for fastest results.

mdfind -onlyin /dir/to/search '(kMDItemFSName==*guess1* || kMDItemFSName==*guess2*)' \
                     '&& (kMDItemFSName=*.extension1 || kMDItemFSName=*.extension2)'

find is slow. grep and other text search tools are much faster. Unless you think you're going to find the needle in the haystack with the first shot, you're probably better off doing a find into a temporary file, e.g. find . -print > /tmp/find.out, and then searching in that file for file names that meet your search criteria.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .