How to count number of files in each directory?

前端 未结 17 2719
小蘑菇
小蘑菇 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 07:50

    I edited the script in order to exclude all node_modules directories inside the analyzed one.

    This can be used to check if the project number of files is exceeding the maximum number that the file watcher can handle.

    find . -type d ! -path "*node_modules*" -print0 | while read -d '' -r dir; do
        files=("$dir"/*)
        printf "%5d files in directory %s\n" "${#files[@]}" "$dir"
    done
    

    To check the maximum files that your system can watch:

    cat /proc/sys/fs/inotify/max_user_watches
    

    node_modules folder should be added to your IDE/editor excluded paths in slow systems, and the other files count shouldn't ideally exceed the maximum (which can be changed though).

    0 讨论(0)
  • 2020-12-07 07:52

    Here's one way to do it, but probably not the most efficient.

    find -type d -print0 | xargs -0 -n1 bash -c 'echo -n "$1:"; ls -1 "$1" | wc -l' --
    

    Gives output like this, with directory name followed by count of entries in that directory. Note that the output count will also include directory entries which may not be what you want.

    ./c/fa/l:0
    ./a:4
    ./a/c:0
    ./a/a:1
    ./a/a/b:0
    
    0 讨论(0)
  • 2020-12-07 07:52

    Everyone else's solution has one drawback or another.

    find -type d -readable -exec sh -c 'printf "%s " "$1"; ls -1UA "$1" | wc -l' sh {} ';'
    

    Explanation:

    • -type d: we're interested in directories.
    • -readable: We only want them if it's possible to list the files in them. Note that find will still emit an error when it tries to search for more directories in them, but this prevents calling -exec for them.
    • -exec sh -c BLAH sh {} ';': for each directory, run this script fragment, with $0 set to sh and $1 set to the filename.
    • printf "%s " "$1": portably and minimally print the directory name, followed by only a space, not a newline.
    • ls -1UA: list the files, one per line, in directory order (to avoid stalling the pipe), excluding only the special directories . and ..
    • wc -l: count the lines
    0 讨论(0)
  • 2020-12-07 07:53

    This prints the file count per directory for the current directory level:

    du -a | cut -d/ -f2 | sort | uniq -c | sort -nr
    
    0 讨论(0)
  • 2020-12-07 07:55

    This will give the overall count.

    for file in */; do echo "$file -> $(ls $file | wc -l)"; done | cut -d ' ' -f 3| py --ji -l 'numpy.sum(l)'
    
    0 讨论(0)
  • 2020-12-07 07:56

    Assuming you have GNU find, let it find the directories and let bash do the rest:

    find . -type d -print0 | while read -d '' -r dir; do
        files=("$dir"/*)
        printf "%5d files in directory %s\n" "${#files[@]}" "$dir"
    done
    
    0 讨论(0)
提交回复
热议问题