If you know about the mdfind command that lets you perform Mac OS X Spotlight searches at the command line (The Power of mdfind, O’Reilly), then you know it’s a good start but ultimately unsatisfactory. I made up a shell script mdfindi that helps me interactively navigate the results of mdfind when I SSH into my home computer. Of course I keep the script on my Dropbox as mentioned in an earlier post so that it is available to all of my computers.

The Problem

The existing mdfind command returns a list of all files that match the word or words you provide it as arguments, but the result is long and unsorted. Below I see that I would get 899 files listed if I look for the word “wedding” with mdfind:

$ mdfind wedding | wc -l
    899

I can help myself by refining the search a bit:

$ mdfind brian wedding | wc -l
    45

What I want is to present an organized view at the command line like the nice divisions that Mac OS X provides when you use the magnifying glass in the upper right corner:


From the magnifying glass, Spotlight search results are organized.

A Problem I Am Not Solving

It is possible to perform special searches such as, “Look for files with this keyword and created after this date,” but the method of specifying these searches is rather laborious. If I ever have to make such searches, I might add that to the mdfindi wrapper script, but it hasn’t come up yet.

The Solution

The mdfindi script performs the Spotlight search and processes the results to present them in a (semi-)organized fashion. It first categorizes all the files that are returned by suffix (file type, presumably), and presents you with the choice of which file type you would like to further explore. I find that usually I am looking for an old email, so emlx is often what I want.

$ mdfindi wedding
Search command: mdfind wedding

File Type     Count
emlx          13   
txt           9    
pdf           9    
xml           2    
webhistory    2    
unix          2    
net)          1    
msf           1    
lst           1    
html          1    
htm           1    
content       1    
PANIC         1    
(too long)    1 

Enter file type to list: 

Since I am looking for an email message, I type emlx and hit return. What I get is a numbered list of files (filtered through the more command).


A list of files to try out.

Hmm, I cannot tell which message I want. If I had written a cool ncurses-based program I could have a preview pane, etc, etc, but I didn’t, so don’t complain. Instead I’ll hit ‘q’ to quit more, and at the prompt, I’ll try examining the first file:

Enter file number to display:  1

Now I get a more dump of the file to see if it’s what I’m looking for, and…it is! If it wasn’t, I would quit more by typing ‘q’ and be returned to the list of files where I could enter a different number, or I could type ‘b’ to back up to the previous screen and see the list of file types again.


Results of mdfindi.