Get the App
SLTechnology News&Howtos  ›  Development  › 

How to count the number of files in the directory under Linux

Shulou Source: shulou.com Published: 2022-06-01 16:00:55 09月22日 Update

This article mainly introduces how to count the number of files under the directory under Linux, which has a certain reference value, and interested friends can refer to it. I hope you will gain a lot after reading this article.

Everything in the Linux system is always files, so how to count the number of files in the directory?

Count the number of files in the directory

The easiest way to count the files in the directory is to use ls to output one file per row and pass the output to wc to calculate the number through the pipe character:

[root@localhost ~] # ls-1U / etc | wc-l

Executing the above command displays the sum of all files, including directories and symbolic links. The-1 option indicates that one file is listed per line, and-U tells ls not to sort the output, which makes the command execute faster. The ls-1U command does not count hidden files. If you want to calculate only the files and not the directories, use the following command:

[root@localhost ~] # ls-1Up / etc | grep-v / | wc-l

The-p option forces ls to append the slash (/) indicator to the directory. The output is passed through the pipe character to the grep-v command, excluding rows that contain slashes, and counting the number. For better control over the listed files, use the find command instead of ls:

[root@localhost ~] # find / etc-maxdepth 1-type f | wc-l

The-type f option tells find to list only files (including hidden files), and-maxdepth 1 restricts the search to first-level directories.

Files in recursive statistical directory

If you want to count the number of files in the directory and include those in the subdirectory, you can use the find command:

[root@localhost ~] # find / etc-type f | wc-l

Another command used to count files is tree, which lists the contents of the directory in a tree format:

[root@localhost ~] # yum-y install tree [root@localhost ~] # tree / root

The bottom of the output shows how many directories and files there are.

Thank you for reading this article carefully. I hope the article "how to count the number of documents in the directory under Linux" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: File directory statistics quantity command article output content slash pipe wrong value mission interest at the same time subitems subdirectories bottom sum instructions Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Microsoft Apple Shulou Tech Info MySQL