This tutorial will show you how to count the number of files/folders in a directory on Linux, both recursively and non-recursively.
The wc Command
The wc (word count) command counts lines and words. It’s useful here as we’ll use it to count the outputted lines from various tools which list the files in a directory or directories.
The below examples will show you how to use the wc command to count files. If you want to know more about it, you can check out the full user manual by running:
Counting Files/Directories in a Directory
By combining the ls command and wc command, the number of files in a directory can be counted:
ls /path/to/directory | wc -l
The output of the ls command is piped to the input of the wc command, which then counts the number of lines present – which will be one for each file.
Include Hidden Files
To include hidden files in the count, add the -a option to the ls command:
ls -a /path/to/directory | wc -l
Counting Files/Directories Recursively
The ls command only lists the number of files in a directory – not those inside any present sub-directories.
To do this, combine the find command and wc command:
find /path/to/directory | wc -l
If you want only to count files and not directories, you can add the -type option to limit the results to files only:
find /path/to/directory -type f | wc -l
You can, of course, use any combination of options available to the find command to count only certain files.
Hidden Files and the Find Command
The find command will include hidden files by default; they can be excluded with this neat bit of regex and the -not -path options:
find /path/to/directory -not -path '*/\.*' | wc -l
This will exclude any files starting with ‘.’ (period character) – which on Linux denotes a hidden file.