Locate via Spotlight on OS X
February 5, 2012
The locate
command is a standard and widely-used tool on most Unix
systems for finding filenames which match a given pattern. The
database is maintained by updatedb
. Similarly, the Spotlight tool
in Mac OS X is a fast and efficient way to search the names and
contents of files. The command-line tool mdfind
can be used to
query the same metadata database. New installations of OS X, however,
come with locate
disabled:
$ locate foo
WARNING: The locate database (/var/db/locate.database) does not exist.
To create the database, run the following command:
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
Please be aware that the database can take some time to generate; once
the database has been created, this message will no longer appear.
Rather than enabling locate and updatedb using launchctl
, and thus
maintaining two separate databases, one can instead define a locate
function which uses mdfind
to query the metadata database that’s
already being maintained by OS X and used by Spotlight. To do so,
add the following to your .bashrc
or .zshrc
as the case may be:
function locate { mdfind "kMDItemDisplayName == '$@'wc"; }
Via Mac OS X Hints.