How to count number of files in each directory?

前端 未结 17 2720
小蘑菇
小蘑菇 2020-12-07 07:05

I am able to list all the directories by

find ./ -type d

I attempted to list the contents of each directory and count the number of files i

相关标签:
17条回答
  • 2020-12-07 08:09
    find . -type f | cut -d/ -f2 | sort | uniq -c
    
    • find. -type f to find all items of the type file
    • cut -d/ -f2 to cut out their specific folder
    • sort to sort the list of foldernames
    • uniq -c to return the number of times each foldername has been counted
    0 讨论(0)
  • 2020-12-07 08:09

    Slightly modified version of Sebastian's answer using find instead of du (to exclude file-size-related overhead that du has to perform and that is never used):

     find ./ -mindepth 2 -type f | cut -d/ -f2 | sort | uniq -c | sort -nr
    

    -mindepth 2 parameter is used to exclude files in current directory. If you remove it, you'll see a bunch of lines like the following:

      234 dir1
      123 dir2
        1 file1
        1 file2
        1 file3
          ...
        1 fileN
    

    (much like the du-based variant does)

    If you do need to count the files in current directory as well, use this enhanced version:

    { find ./ -mindepth 2 -type f | cut -d/ -f2 | sort && find ./ -maxdepth 1 -type f | cut -d/ -f1; } | uniq -c | sort -nr
    

    The output will be like the following:

      234 dir1
      123 dir2
       42 .
    
    0 讨论(0)
  • I tried with some of the others here but ended up with subfolders included in the file count when I only wanted the files. This prints ./folder/path<tab>nnn with the number of files, not including subfolders, for each subfolder in the current folder.

    for d in `find . -type d -print` 
    do 
      echo -e "$d\t$(find $d -maxdepth 1 -type f -print | wc -l)"
    done
    
    0 讨论(0)
  • 2020-12-07 08:10

    This should return the directory name followed by the number of files in the directory.

    findfiles() {
        echo "$1" $(find "$1" -maxdepth 1 -type f | wc -l)
    }
    
    export -f findfiles
    
    find ./ -type d -exec bash -c 'findfiles "$0"' {} \;
    

    Example output:

    ./ 6
    ./foo 1
    ./foo/bar 2
    ./foo/bar/bazzz 0
    ./foo/bar/baz 4
    ./src 4
    

    The export -f is required because the -exec argument of find does not allow executing a bash function unless you invoke bash explicitly, and you need to export the function defined in the current scope to the new shell explicitly.

    0 讨论(0)
  • 2020-12-07 08:10

    THis could be another way to browse through the directory structures and provide depth results.

    find . -type d  | awk '{print "echo -n \""$0"  \";ls -l "$0" | grep -v total | wc -l" }' | sh 
    
    0 讨论(0)
提交回复
热议问题