Use Spotlight from the Command Line with mdfind
Spotlight is one of my favorite features of Mac OS X, I probably use it more than even the Dock. Being able to hit command-space to quickly locate documents, emails, and launch Applications is endlessly useful. For some of us, it’s necessary to be in the terminal, and wouldn’t it be cool to have this ultra seach feature in the command line? Well it’s there, open up your Terminal (or iTerm) and explore mdfind, the command line version of Spotlight.
Even if you’re new or oblivious to the Unix underpinnings of Mac OS X, you can try this out. Open your terminal and type mdfind, you’ll get some directions thrown back at you because you didn’t specify a search query:
mdfind: no query specified.
Usage: mdfind [-live] [-onlyin directory] query
list the files matching the query
query can be an expression or a sequence of words
-live Query should stay active
-onlyin dir Search only within given directory
-0 Use NUL (``\0'') as a path separator, for use with xargs -0.
example: mdfind image
example: mdfind "kMDItemAuthor == '*MyFavoriteAuthor*'"
example: mdfind -live MyFavoriteAuthor
If this looks confusing, it’s not. Say you want to find a file named ‘recipe’ and you know it’s in your documents folder, you’d type:
$ mdfind recipes -onlyin ~/Documents/
If you have a ton of recipes, it’s probably a good idea to pipe the output into more, as shown below:
$ mdfind recipes -onlyin ~/Documents/ | more
By piping the results through more, it allows you to view a screenful at a time. You can exit more by hitting control-c.
There’s much more to be done with the mdfind command, but we’ll keep it simple for now. Beyond curiosity, the mdfind command is probably more useful to sysadmins, unix geeks, shell scripters, and programmers than the standard Mac user. For the rest of us, command-space is where it’s at, and we’re not complaining.