A Better Command Line Find


If you're coming to OS X from UNIX, like me, then you're probably comfortable with the command line and you probably know your way around the find command. I use it all the time for finding files. Since I upgraded to Tiger, I use Spotlight a lot more, but there are still times when I want to find things on the command line. Apple has thoughtfully provided a Spotlight enabled version of find called mdfind

Using mdfind is easy: just type the command followed by whatever you'd enter in the Spotlight search box. You'll get back a list of files, just like from find, that can be used with other shell commands. The difference is that if you type mdfind "BYU Purchasing" you'll not only find files with the string "BYU Purchasing" in the filename, but also inside the file itself.

Another difference is that mdfind searches the entire disk index by default. To limit it to certain directories, you can use the switch -onlyin followed by the directory name. Because mdfind is using the Spotlight index, it's very fast--much faster than a regular find.

mdfind can search a file's metadata as well. The tricky part is that you have to know the name of the metadata tags that you're interested in. The command mdls can be used to list the metadata attributes of a file, once you know the attribute, you can use it to search for files with that same attribute in an expression. For example, the following expression finds all the HTML files in my Documents folder:

mdfind -onlyin ~/Documents "kMDItemKind  == "HTML document"    

The command mdimport -A will show you all the attributes that you can search by and give a short description of each. For example, you can use 'kMDItemRedEyeOnOff' to tell you whether 'red eye' correction was on or off.

Naturally, mdfind can only find things in the index and Spotlight doesn't index the entire harddrive or even every file type. If you want to put something in the index that Spotlight doesn't do normally, you can use the mdimport command to do that. The other command used to control indexing is mdutil which can switch indexing on or off for a volume, erase and rebuild an index, and show the status of indexing.

For some things, I suspect, I still use the comfortable old find command, but as fast as mdfind is, I'll be turning to it more and more often.


Please leave comments using the Hypothes.is sidebar.

Last modified: Thu Oct 10 12:47:19 2019.