Although not very often, there are times when you need to find out how many files are in a given directory. For example, if you run out of inodes on your Linux system, you’ll 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 in Linux.
Count Files in Directory
The simplest way to count files in a directory is to list one file per line with ls
and pipe the output to wc
to count the lines:
ls -1 DIR_NAME | wc -l
The command above will give you a sum of all files, including directories and symlinks. If you want to count only files and not include the directories you could use the following:
ls -1p DIR_NAME | grep -v / | wc -l
The -p
option tells ls
to append slash (/
) indicator to directories. The output is piped to the grep -v
command that exclude the 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 instead of ls
:
find DIR_NAME -maxdepth 1 -type f | wc -l
-type f
option tells find
to list only files (including dotfiles), and -maxdepth 1
limit search to the first-level directory.
Recursively Count Files in Directory
To recursively count files in directory run the find
command as follows:
find DIR_NAME -type f | wc -l
Another command that can be used to count files is tree
that lists contents of directories in a tree-like format:
tree DIR_NAME
The last line of output will show the total number of files and directories listed:
15144 directories, 91311 files
Conclusion
We have shown you how to count files in directory using the ls
, find
and tree
commands.
If you have any questions or feedback, feel free to leave a comment.