Count of files in each sub-directories

Assuming you want a recursive count of files only, not directories and other types, something like this should work:

find . -maxdepth 1 -mindepth 1 -type d | while read dir; do
  printf "%-25.25s : " "$dir"
  find "$dir" -type f | wc -l
done

This task fascinated me so much that I wanted to figure out a solution myself. It doesn't even take a while loop and MAY be faster in execution speed. Needless to say, Thor's efforts helped me a lot to understand things in detail.

So here's mine:

find . -maxdepth 1 -mindepth 1 -type d -exec sh -c 'echo "{} : $(find "{}" -type f | wc -l)" file\(s\)' \;

It looks modest for a reason, for it's way more powerful than it looks. :-)

However, should you intend to include this into your .bash_aliases file, it must look like this:

alias somealias='find . -maxdepth 1 -mindepth 1 -type d -exec sh -c '\''echo "{} : $(find "{}" -type f | wc -l)" file\(s\)'\'' \;'

Note the very tricky handling of nested single quotes. And no, it is not possible to use double quotes for the sh -c argument.


find . -type f | cut -d"/" -f2 | uniq -c

Lists a folders and files in the current folder with a count of files found beneath. Quick and useful IMO. (files show with count 1).

Tags:

Linux

Bash