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.

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

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

Output would only contain...

/home/foo/
/home/foo/someotherdir/food/
/food/
/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
1  
Perhaps just use find? find / -wholename '*foo*' -type d? –  Zoredache Mar 2 '12 at 21:19

4 Answers 4

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

#!/bin/bash
f=$(readlink $1)
if [ -d "$f" ]
then
    echo $1
fi

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

 
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.