How to count the files in the directory under Linux

Time:2021-6-21

In this article, we’ll show you several different ways to find the number of files in a Linux directory.
Count the number of files in the directory
The simplest way to count the files in the directory is to use ls to list one file per line, and pass the output to WC through the pipeline character to calculate the quantity

[[email protected] ~]# ls -1U /etc |wc -l
Executing the above command will display the sum of all files, including directories and symbolic links- The – U option tells LS not to sort the output, which makes the execution of the command faster. The LS – 1U command does not compute hidden files. If you want to calculate only files and not directories, use the following command:

[[email protected] ~]# ls -1Up /etc |grep -v /|wc -l
-The P option forces ls to attach the slash (/) indicator to the directory. The output is passed to the grep – V command through the pipe character, excluding the lines containing slashes, and calculating the number.
For better control of the listed files, use the find command instead of LS:

[[email protected] ~]# find /etc -maxdepth 1 -type f |wc -l
-The type F option tells find to list only files (including hidden files), – maxdepth 1 limits the search to the first level directory.

Recursively count files in directory
If you want to count the number of files in the directory, including those in subdirectories, you can use the find command:

[[email protected] ~]# find /etc -type f|wc -l
Another command used to count files is tree, which lists the contents of the directory in tree format

[[email protected] ~]# yum -y install tree
[[email protected] ~]# tree /root
How to count the files in the directory under Linux
How many directories and how many files are displayed at the bottom of the output.

summary
In this article, we’ll show you several different ways to find the number of files in a Linux directory.