Use GNU find to show only the leaf directories

前端 未结 7 689
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 18:57

I\'m trying to use GNU find to find only the directories that contain no other directories, but may or may not contain regular files.

My best guess so far has been:

7条回答
  •  难免孤独
    2020-12-04 19:56

    I have some oddly named files in my directory trees that confuse awk as in @AhmetAlpBalkan 's answer. So I took a slightly different approach

      p=;
      while read c;
        do 
          l=${#c};
          f=${p:0:$l};
          if [ "$f" != "$c" ]; then 
            echo $c; 
          fi;
          p=$c; 
        done < <(find . -type d | sort -r) 
    

    As in the awk solution, I reverse sort. That way if the directory path is a subpath of the previous hit, you can easily discern this.

    Here p is my previous match, c is the current match, l is the length of the current match, f is the first l matching characters of the previous match. I only echo those hits that don't match the beginning of the previous match.

    The problem with the awk solution offered is that the matching of the beginning of the string seems to be confused if the path name contains things such as + in the name of some of the subdirectories. This caused awk to return a number of false positives for me.

提交回复
热议问题