I. Introduction
In the Linux system, we often need to query how many files are contained in the folder. This article will introduce three methods of querying the number of files in a folder in Linux to help you easily obtain the information you need.
2. Method
1. Using ls
commands and wc
commands
Use ls
the command's -l
options and the pipe operator |
to combine wc
the command to count the number of files:
ls -l | grep "^-" | wc -l
This command will list all the files and subfolders in the folder, and use grep
the command to filter out -
the lines starting with (indicating files), and then use wc -l
the command to count the number of lines, that is, the number of files.
2. Using ls
commands and grep
commands
Use ls
the command's -p
options and the pipe operator |
to combine grep
the command to count the number of files:
ls -p | grep -v / | wc -l
This command will list all the files and subfolders in the folder, and use grep -v /
the command to filter out /
the lines ending with (indicating subfolders), and then use wc -l
the command to count the number of lines, that is, the number of files.
3. Use find
commands to recursively query
Use find
the command to find files recursively, and use wc
the command to count the number of files:
find /path/to/folder -type f | wc -l
Replace /path/to/folder
with the folder path you want to query. This command will recursively find all files under the specified folder, and use wc -l
the command to count the number of lines, that is, the number of files.
Note : In the first and second method, subfolders within a folder are not counted. If you want to include the number of files in subfolders, you can use the third method.
3. Conclusion
The above are the three methods for querying the number of files in a folder in the Linux system.
According to your needs and scenarios, you can choose a suitable method to obtain the number of files.