How to Count Files in a Directory in Linux

By 

Updated on

2 min read

Count Files in Directory in Linux

Sometimes you need to find out how many files are in a directory. For example, if you run out of inodes on your Linux system, you may need to identify a directory that contains thousands or millions of files.

This article shows several ways to count files in a directory in Linux using ls, find, and tree.

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:

Terminal
ls -1U DIR_NAME | wc -l

The command above will give you a sum of all files, including directories and symlinks. The -1 option means list one file per line and -U tells ls not to sort the output, which makes the command faster.

The ls -1U command does not count hidden files (dotfiles).

If you want to count only files and not include the directories use the following:

Terminal
ls -1Up DIR_NAME | grep -v / | wc -l

The -p option forces ls to append a slash (/) to directory names. The output is piped to the grep -v command, which excludes the directories.

To have more control over what files are listed, use the find command instead of ls:

Terminal
find DIR_NAME -maxdepth 1 -type f | wc -l

The -type f option tells find to list only files, including dotfiles, and -maxdepth 1 limits the search to the first-level directory.

Recursively Count Files in Directory

To count all files in the current directory and its subdirectories, run:

Terminal
find . -type f | wc -l
output
42

In this example, the command found 42 regular files under the current directory and all of its subdirectories.

To count files in a specific directory, pass the path as an argument:

Terminal
find /path/to/directory -type f | wc -l

Another command that can be used to count files is tree, which lists directory contents in a tree-like format:

Terminal
tree DIR_NAME

If tree is not installed on your system, you can usually install it from your distribution’s package repository.

The last line of output shows the total number of files and directories listed:

output
15144 directories, 91311 files

In this example, tree found 91,311 files and 15,144 directories under DIR_NAME.

Conclusion

We have shown you how to count files in a directory using the ls, find, and tree commands.

For more on working with files from the command line, see the find command guide .

Tags

Linuxize Weekly Newsletter

A quick weekly roundup of new tutorials, news, and tips.

About the authors

Dejan Panovski

Dejan Panovski

Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 800+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.

View author page