I'm trying to figure out how to perform wildcard searches for filenames with mdfind on OsX? I tried:
mdfind -name "*.pdf" but it didn't work.
EDIT: I want to be able to find names like "test*.pdf"
Ask Different is a question and answer site for power users of Apple hardware and software. It only takes a minute to sign up.Sign up to join this community
This should work:
mdfind "kMDItemDisplayName == test*.pdf"
Enclose the pattern in single quotes and add 'c' to match case-insensitively:
mdfind "kMDItemDisplayName == 'test*.pdf'c"
Here is a list of available attributes. You can combine multiple attribute/value pairs with
macOS ships with the regular
find command, and
mdfind is not a replacement for
If you really just want to search the current directory for all pdf files, you should probably just do
find . -name '*.pdf'
mdfind searches by file content and metadata, and it searches your entire hard drive instead of just a single directory — on my system
mdfind pdf finds tens of thousands of results.
If you must use mdfind, because it's faster, you have a few options to limit the results, for example:
mdfind pdf -onlyin . mdfind 'kMDItemFSName = *.pdf' -onlyin . mdfind 'kMDItemContentTypeTree = *.pdf' -onlyin .
mdls to learn what metadata is available for a file, and the syntax for pattern matching is very minimalist since it needs to match the database index of your filesystem.
Alternatively you can
grep, giving the speed of
mdfind and full regex matching on the file path. For example:
mdfind pdf -onlyin . | grep 'pdf$'
One final caveat is
mdfind does not search your actual file system, it only searches the spotlight database which may be missing parts of the filesystem or inaccurate. Use
find if you require reliable results. Use
mdfind when you require speed over accuracy and when you need complicated search terms (eg find all pdf files that were created within a specific date range and contain a phrase of text).
When explicitly searching for filenames, my experience is that the
kMDItemFSName attribute provides more concise results. Another suggestion: add the
d comparison modifier (insensitive to diacritical marks) to e.g. match a file called "Entrée Menu.pdf" when searching for "entree":
mdfind 'kMDItemFSName == "*entree*"cd'
If you find yourself frequently wanting to use Spotlight to search for filenames by glob patterns, it might be worth it to wrap it into a script by saving this code into a
mdfindfile on your path:
#!/usr/bin/env bash # case-insensitive search for $1, maybe in dir $2 case "$#" in 0) echo "usage: $(basename $0) PATTERN [DIR]" echo "" echo " Lists paths of files matching PATTERN in DIR or below" ;; 1) exec mdfind "kMDItemDisplayName == '$1'c" ;; *) exec mdfind "kMDItemDisplayName == '$1'c" -onlyin "$2" ;; esac
Then you can just do
mdfindfile "*.pdf" to search your machine or
mdfindfile "*.pdf" ~/Documents to search below your Documents, or whatever.