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

前端 未结 2 1302
醉梦人生
醉梦人生 2021-01-27 04:06

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

/storage/BCC9F9D00663A8043F8D73369E920632/.todo
/storage/BAE9BBF30CCEF5210534E875FC80D37E/.         


        
相关标签:
2条回答
  • 2021-01-27 04:38

    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
    

    Or

    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"
    done
    
    0 讨论(0)
  • 2021-01-27 04:38

    The quick and easy answer for stripping off a file name and showing only the directory it’s in is dirname:

    #!/bin/bash
    STORAGEFOLDER='/storage'
    find "$STORAGEFOLDER" -name .todo  -exec dirname {} \;
    
    0 讨论(0)
提交回复
热议问题