Linux Commands

How to Count the Number of Files in a Directory on Linux

If you are working on an operating system, it is essential to count the available files in the directory as it provides a brief overview of the contents. It lets you limit the storage and get the details of unnecessarily large files. Moreover, as a Bash script user, you can count the number of files to automate the specific tasks and limit the numbers in them.

However, many beginners want to know how to check the number of files. So, in the blog, we included multiple commands to count the number of available files in the directory quickly.

How to Count the Number of Files in a Directory on Linux

Let’s divide this guide into multiple parts where we will explain the different commands to count the number of files in Linux.

1. The Wc Command
You can use the “wc” command with “ls” to check the number of files in a directory. For example, let’s count the number of available files in the “Downloads”.

ls . | wc -l

The “-l” option instructs to count the lines rather than words. If you want to count the hidden files, use the “-a” option.

ls -a  | wc -l

Counting specific types of files is also simple as you only need to run the following command. For example, let’s count the “.js” files:

ls *.js | wc -l

To count all visible and hidden files in a directory, you can also use the following command:

find . -type f | wc -l

Note: The pervious command includes the hidden files.

2. The Tree Command
The “tree” command is useful while dealing with the nested subdirectories as this command provides a clear information about your files. Moreover, the “tree” also shows the summary at the end, including the number of files. In case your system doesn’t have the “tree” utility, run the following command:

sudo apt install tree (Ubuntu)
sudo dnf install tree (Fedora)
sudo yum install tree (RHEL based OS)

Note: By default, the “tree” command is recursive which means that the output can include all subdirectories.

tree

Since the previous command doesn’t include the hidden files, run the following command to display them:

tree -a

Conclusion

This is all about the multiple methods of counting the files in a directory. Remember that counting the number of files in a directory can be beneficial for you to perform the regular system checks and storage cleanup. You should use the “tree” command for a brief information in the directory.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.