How do I use the locate command within a specified directory?

I am using the locate command on Linux. My current usage of it searches through the entire filesystem. I only want it to search within a specific directory. How can I do this?


Another approach would be to use the pattern matching in locate:

locate '/some/directory/*filename*'

Compare the output of the commands below:

$ locate tmpfile
/usr/lib64/perl5/auto/POSIX/tmpfile.al
/usr/share/man/fr/man3/tmpfile.3.gz
/usr/share/man/ja/man3/tmpfile.3.gz
/usr/share/man/man3/tmpfile.3.gz
/usr/share/man/man3p/tmpfile.3p.gz
$
$ locate '/usr/lib64/*tmpfile*'
/usr/lib64/perl5/auto/POSIX/tmpfile.al
$ 

locate /usr/lib*tmpfile* gives the same result.


Create slocate database for your specific directory with:

updatedb -U /path/to/directory

and search with:

locate <search_string>

UPDATE

This works fine on my Gentoo system but CentOS doesn't include -U option. So, you can try below instead:

Build the database with:

# updatedb -U /path/to/dir -o dir_locate.db

and search:

# locate -d dir_locate.db <search_string>