How to Count Files in a Directory on Linux and FreeBSD
I was moving backups with rsync. I had no doubts the contents were identical (I’d done it before), but I decided to check the number of files on both sides.
To count the files in a directory and all its subdirectories, use:
ls -l -R /data_b | grep ^- | wc -l
How it works
It’s a compound command, so here it is piece by piece:
ls -l -R /data_b— prints a detailed list of all files in /data_b and its subdirectories;grep ^-— keeps only lines starting with “-“, i.e. regular files (directory lines start with “d”, links with “l”);wc -l— counts the lines, i.e. the files.
I’m using FreeBSD as the example because that’s where I needed it, but the commands are standard and work on Linux too.
Note: the total line in the ls -l output is not the number of files but the space they take up (in blocks). People sometimes mistake it for a file count.
Counting by name pattern
You can use regular expressions in grep. For example, the number of .so files in /lib:
ls -l -R /lib | grep ^- | grep '\.so$' | wc -l
More ways: find and ls (Linux)
Later I noted a few more commands for Linux (tested on Debian).
Files in the current directory only, without subdirectories:
find . -maxdepth 1 -type f | wc -l
The fastest option for huge directories is ls -f (no sorting). But it counts every entry: subdirectories, hidden files and the special “.” and “..”.
ls -f . | wc -l
Recursively, including all subdirectories:
find . -type f | wc -l
The number of directories (including the current one) — change f to d:
find . -type d | wc -l
Only files with the .log extension, recursively:
find . -type f -name "*.log" | wc -l
