Disco Disco - 1 year ago 52
Linux Question

Print the directory where the 'find' linux command finds a match

I have a bunch of directories; some of them contain a '.todo' file.


I'd like the 'find' command to print me only the directory, like this


here's what I have so far, but it lists the '.todo' file as well

find $STORAGEFOLDER -name .todo -exec ls -l {} \;

Should be dumb stupid, but i'm giving up :(

Answer Source

To print the directory name only, use -printf '%h\n'. Also recommended to quote your variable with doublequotes.

find "$STORAGEFOLDER" -name .todo -printf '%h\n'

If you want to process the output:

find "$STORAGEFOLDER" -name .todo -printf '%h\n' | xargs ls -l

Or use a loop with process substitution to make use of a variable:

while read -r DIR; do
    ls -l "$DIR"
done < <(exec find "$STORAGEFOLDER" -name .todo -printf '%h\n')

The loop would actually process one directory at a time whereas in xargs the directories are passed ls -l in one shot.

To make it sure that you only process one directory at a time, add uniq:

find "$STORAGEFOLDER" -name .todo -printf '%h\n' | uniq | xargs ls -l


while read -r DIR; do
    ls -l "$DIR"
done < <(exec find "$STORAGEFOLDER" -name .todo -printf '%h\n' | uniq)

If you don't have bash and that you don't mind about preserving changes to variables outside the loop you can just use a pipe:

find "$STORAGEFOLDER" -name .todo -printf '%h\n' | uniq | while read -r DIR; do
    ls -l "$DIR"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download