user784637 user784637 - 5 months ago 29
Linux Question

How to count number of files in each directory?

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 in each directory by using the following command

find ./ -type d | xargs ls -l | wc -l


But this summed the total number of lines returned by

find ./ -type d | xargs ls -l


Is there a way I can count the number of files in each directory?

Answer

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