Take the 2-minute tour ×
Ask Different is a question and answer site for power users of Apple hardware and software. It's 100% free, no registration required.

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?

share|improve this question
add comment

4 Answers 4

up vote 3 down vote accepted

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)"
share|improve this answer
2  
Obligatory note: there are downsides to parsing ls. –  George Garside May 1 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. –  200_success May 1 at 23:28
add comment

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.)

share|improve this answer
add comment

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)'
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.