Linux

How to Count Files in Directories on Linux

How to Count Files in Directories on Linux

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:

tree DIR_NAME

The last line of output will show the total number of files and directories registered:

15144 directories, 91311 files

Conclusion

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.

Related posts

How to Install PyroCMS with Nginx and Let’s Encrypt SSL on CentOS 8

Linux

How to Install Memcached on Ubuntu 20.04 LTS

Linux

How to Install PostgreSQL on Ubuntu 20.04

Linux

How to Install Django on Ubuntu 20.04 LTS

Linux

How to Install Elasticsearch, Logstash, and Kibana (ELK Stack) on Ubuntu 20.04

Linux

How to Install Tomcat 9 on Ubuntu 20.04

Linux

How to Install and Use a Curl on Ubuntu 20.04

Linux

How to Install WordPress with Nginx on Ubuntu 20.04 LTS

Linux

Fedora 31: How to Install Fuel CMS with Nginx

Howto