Is is it possible to use the locate command to only find directories? To rephrase, I want to search for a directory, and exclude any result that is not a directory, such as files or symlinks to files.

While not necessary, I would like the solution to also return symlinks to other directories (but again, not files).

Lastly, I would like to exclude directories within foo, with one exception. If a subdirectory of foo also contains a subdirectory with a name containing foo, I would prefer it be returned as well.

If the following files and directories exist...

/var/www/foo -> /home/foo/
/var/www/food -> /home/food/index.html

Output would only contain...

/var/www/foo -> /home/foo/

Thanks in advance.

Edit: Thank you for the responses. I am very deliberate in titling this for the locate command and not find.

  • 1
    Perhaps just use find? find / -wholename '*foo*' -type d?
    – Zoredache
    Mar 2, 2012 at 21:19

4 Answers 4


Maybe a litte tricky but here it comes:

locate foo | xargs file -NF '|' |grep '| directory' | sed 's/| directory//g'
  • 2
    slightly ugly, but faster than find on the whole filesystem :-) IMPORTANT CAVEAT: This will only find stuff in the locate command's database (some systems don't run updatedb as root, so there may be some missing items...)
    – voretaq7
    Mar 2, 2012 at 21:56

Locate only reads preprepared databases and not the filesystem.

Using find

directories containing foo

find /path -name '*foo*' -type d

links that contain foo, you need to read the link and test to see if the destination is a directory which requires a script

f=$(readlink $1)
if [ -d "$f" ]
    echo $1

use it like this

find /path -name '*foo*' -type l -exec script {} \;
  • I know locate only uses the prepared database from updatedb, and not the filesystem. I specifically was hoping to not use find, but rather locate because it runs faster.
    – Tor
    Mar 4, 2012 at 14:50
locate foo | sed 's%/[^/]*$%/%'

Edit: This just snaps all info out after the last slash.


This one will do the job:

locate foo | grep "foo[^/]*/$"

It will be much quicker than the find options available but with the standard locate caveat that it could be up to 24 hours out of date.

  • 1
    Does your version of locate append / to directories? Mine doesn't seem to. (mlocate 0.24) Mar 3, 2012 at 0:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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