Whenever you are probably monitoring disk space on your system all the time. And as well as, you may want to know How many files and directories are in the given directory, or in many different directories or subdirectories.
Right now In this tutorial guide, you will learn how to count number of files in directory and subdirectory unix/linux. And as well as how to count hidden files and directories in unix/Linux system.
So, this tutorial guide will help you how you can easily count files and directories in a directory on Linux using ls
, find
and tree
commands.
Count Files in Directory and Subdirectories in Linux/Unix
Here are some linux/unix commands (ls
, find
and tree
commands) to count number of files in a directory and subdirectories:
- Count Files using wc
- Linux Count Files in Directory Recursive
- Count Files using tree
- Count Hidden Files Linux
Count Files using wc
Now, you will learn the easiest way to count files in a directory on Linux using the “ls” command and pipe it with the “wc -l” command, As shown below:
ls | wc -l
Note that, The “wc” command is used on Linux in order to print the bytes, characters or newlines count.
Now, i will run the “ls” command on the “/html” directory and pipe it with the “wc” command, as shown below:
ls /html | wc -l
The output will be as shown below:
500
Linux Count Files in Directory Recursive
Count files recursively on Linux using the “find” command and pipe it with the “wc” command. As shown below:
find <directory> -type f | wc -l
For example, if you want to recursively count files in the “/html” directory, you would write the following query:
find /html -type f | wc -l
If you are finding to some error messages with the above command, so you can use the following command on it to count files recursively in direcotry:
find /etc -type f 2> /dev/null | wc -l
Count Files using tree
If you want to count files and directories in a directory. So, you can use “tree” command and to specify the name of the directory to be inspected. As shown below:
tree <directory>
This is very important thinga about the “tree” command, it is not installed on all hosts by default.
If you are having a “tree : command not found” or “tree : no such file or directory”, you will have to install it using sudo privileges on your linux system. By executing the following commands:
sudo apt-get install tree // for Ubunbu/Debian hosts sudo yum install tree // for CentOS/RHEL hosts
Count Hidden Files Linux
If you want to count hidden files and directories in a directory. So, you can use “tree” command with -a parameter. As shown below:
tree -a <directory>
Conclusion
Count files and direcotries in linux tutorial guide, you have learn how to count files and directories in directory using the ls
, find
and tree
commands.