Although not very often, there are times when you need to find out how many files are in a particular directory. For example, if you run out of inodes on your Linux system, everything you need to find which directory contains thousands or millions of files.
In this article, we will show you several different ways to find the number of files in a directory on Linux.
Calculate Files in a Directory
The simplest way to count files in a directory is to register one file per line with ls and pipe the output to wc to count lines:
ls -1 DIR_NAME | wc -l
The above command will give you the sum of all files, including directories and symlinks. If you want to count only files and do not include directories you can use the following:
ls -1p DIR_NAME | grep -v / | wc -l
The -p option tells ls to add the slash (/) indicator to the directory. The output is routed to the grep -v command which excludes directories.
ls -1 also doesn’t count hidden files (dotfiles).
To have more control over what files are listed, you can use the find command rather than ls:
find DIR_NAME -maxdepth 1 -type f | wc -l
-type f option tells find to register only files (including dotfiles), and -maxdepth 1 restricts searches to first level directories.
Count files recursively in the directory
To count files recursively in a directory, run the find command as follows:
find DIR_NAME -type f | wc -l
Another command that can be used to count files is a tree that lists directory contents in a tree-like format:
The last line of output will show the total number of files and directories registered:
15144 directories, 91311 files
We have shown you how to count files in directories using the ls, find and tree commands.
If you have questions or feedback, don’t hesitate to leave a comment.