Count the number of files in a directory and all sub directories in Bash (Unix or Linux)

Counting the numher of files in a directory is easy:

ls | wc -l

Taking the sub directories requires a little more, so I made a script:

#!/bin/sh

ls -a $@ | while read dir
do
find "$dir" | wc -l | tr "\n" "\t"
echo "$dir"
done

Put in to a file, say numfile, make it executeable: chmod +x numfile and run it in the directory you waht to look at. You can also just give the name of the directory as a parameter.

Now, lets say you only want the 15 directories with the most files in them, easy:

./numfiles | sort -n | tail -n 15

Comments are closed.