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?
4 Answers
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.
-
3+1 This is the correct answer. Note that if you include the wildcard, the boundaries become fixed. That is in the above example,
$ locate '/usr/lib64/*tmpfile'
will return no results.– xoferSep 21, 2011 at 4:36 -
If you want more control than simple wildcards can offer, you can always pipe the results of
locate
throughgrep
. Oct 20, 2014 at 16:02
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>
-
3"locate -U" throws an invalid option error... Guessing you meant "updatedb -U"? Also good to note this requires an mlocate.db rebuild (updatedb) if you ever want to search another directory.– gharperSep 21, 2011 at 2:59
-
Oh, on my Gentoo it works fine but CentOS doesn't include this option.– quantaSep 21, 2011 at 3:21
-
-
If you have error like:
updatedb: can not change group of file 'db.db.kHhzFz' to 'mlocate': Operation not permitted
, check how to use updatedb command as an ordinary user on linux.– kenorbOct 18, 2014 at 17:38
The simplest answer I can think of is
locate search_term | grep "/specified/directory"
The better solution might be to use "find" and its path options...
The easiest way is as in the following example:
updatedb -o ~/tmp.db -l0 -U $PWD
locate -d ~/tmp.db "foo"
Change $PWD
into your specific directory.
The example above will create your local database only for the specific directory.
locate
search within a specified directory:alias my_locate="updatedb -U /path/to/yourdir -o /path/to/your_dir_locate.db; locate -d /path/to/dir_locate.db "
Once the alias is effective, on the terminal typemy_locate *foo*
and you're off to the races. You can concatenate database updates and locate search by using the colon character to concat databases. rtfm: linux.die.net/man/8/updatedb