Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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?

share|improve this question

4 Answers 4

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.

share|improve this answer
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. –  xofer Sep 21 '11 at 4:36
    
If you want more control than simple wildcards can offer, you can always pipe the results of locate through grep. –  Ladadadada Oct 20 at 16:02

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...

share|improve this answer

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>
share|improve this answer
2  
"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. –  gharper Sep 21 '11 at 2:59
    
Oh, on my Gentoo it works fine but CentOS doesn't include this option. –  quanta Sep 21 '11 at 3:21
    
Down vote? Could you please leave a comment? –  quanta Sep 21 '11 at 4:44
    
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. –  kenorb Oct 18 at 17:38

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.