[non-perl] mdfind vs. locate

ChrisDolan on 2009-07-26T19:08:54

I've used the "locate" command for many, many years on various POSIX systems. It's a very fast search for filenames containing the specified string on your machine.

Here's a Mac command that simulates "locate" using the Spotlight database:

#!/bin/sh
mdfind "kMDItemFSName == '*$1*'"


It's not as fast as locate, but it is always up to date (as opposed to locate, which relies on cron to reindex the disk periodically). As anyone can guess from the syntax, it's also very flexible. To find all files that originated as email attachments from my friend Glenn, for example, I can do:
mdfind "kMDItemWhereFroms == '*medianinja.com*'"
Or to find all files bigger than about a gigabyte:
mdfind "kMDItemFSSize > 1000000000"
(the WhereFroms search is fast and the size search is dramatically slower, maybe because all files have sizes but not many have kMDItemWhereFroms metadata)

To get a list of the supported keywords, type "mdimport -A"

Update: I found the Spotlight query syntax to be useful


more on mdfind

petdance on 2009-07-26T22:01:29

Here's an article about mdfind I wrote three years ago: http://www.oreillynet.com/pub/a/mac/2006/01/04/mdfind.html.

There's actual Perl code at the end to find the longest songs in my iTunes collection:

$ perl longsongs 9
20:34 "2112" by Rush from "2112"
18:36 "Alice's Restaurant Massacree" by Arlo
    Guthrie from "The Best Of Arlo Guthrie"
...
9:16 "Between I And Thou" by The Mermen from
    "A Glorious Lethal Euphoria"
9:05 "Watermelon In Easter Hay" by Frank Zappa
    from "Joe's Garage"
9:03 "Slow Burn" by Silkworm from "Even A Blind
    Chicken Finds A Kernel Of Corn Now And Then"
9:00 "The Load-Out / Stay" by Jackson Browne from
    "Running On Empty"