Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
Perhaps just use find? find / -wholename '*foo*' -type d? – Zoredache Mar 2 '12 at 21:19
up vote 4 down vote accepted

Maybe a litte tricky but here it comes:

locate foo | xargs file -NF '|' |grep '| directory' | sed 's/| directory//g'
share|improve this answer
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 '12 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 {} \;
share|improve this answer
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 '12 at 14:50
locate foo | sed 's%/[^/]*$%/%'

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

share|improve this answer

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.

share|improve this answer
Does your version of locate append / to directories? Mine doesn't seem to. (mlocate 0.24) – Mark Wagner Mar 3 '12 at 0:19

Your Answer


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.