How to search files or directories on Mac using the command locate

The command locate is present in the Unix system, and its functionality is search files or directories in our system, it uses a database so after we update the database the search is very fast.

These are the steps to use locate on Mac:

Update the database

We need to update the database of files and directories; it is recommended to update the database after a time.

This command to update the database:

sudo /usr/libexec/locate.updatedb

The first time it takes a long time to create the database.

I have a symlink to the binary file, this way you don't need introduce the whole path every time:

sudo ln -s /usr/libexec/locate.updatedb /usr/local/bin/updatedb

Now you can restart the terminal session and updatedb is avaliable.

sudo updatedb

Search a file or directory

The syntax to search a file or directory is simple; you only need put the command locate next to the file or directory name:

locate [target]


locate file.txt

There are a couple extra options (man locate):

-0          Print pathnames separated by an ASCII NUL character (character code 0) instead of default NL
            (newline, character code 10).

-S          Print some statistics about the database and exit.

-c          Suppress normal output; instead print a count of matching file names.

-d database
            Search in database instead of the default file name database.  Multiple -d options are allowed.
            Each additional -d option adds the specified database to the list of databases to be searched.

            The option database may be a colon-separated list of databases.  A single colon is a reference
            to the default database.

            $ locate -d $HOME/lib/mydb: foo

            will first search string ``foo'' in $HOME/lib/mydb and then in /var/db/locate.database.

            $ locate -d $HOME/lib/mydb::/cdrom/locate.database foo

            in /cdrom/locate.database.

                  $ locate -d db1 -d db2 -d db3 pattern

            is the same as

                  $ locate -d db1:db2:db3 pattern


                  $ locate -d db1:db2 -d db3 pattern

            If - is given as the database name, standard input will be read instead.  For example, you can
            compress your database and use:

            $ zcat database.gz | locate -d - pattern

            This might be useful on machines with a fast CPU and little RAM and slow I/O.  Note: you can
            only use one pattern for stdin.

-i          Ignore case distinctions in both the pattern and the database.

-l number   Limit output to number of file names and exit.

-m          Use mmap(2) instead of the stdio(3) library.  This is the default behavior and is faster in
            most cases.

-s          Use the stdio(3) library instead of mmap(2).