You might have come across a lot of files in a directory when searching on your server.
Sometimes, you may want to know how many files are sitting in a given directory.
In this tutorial, we are going to see how you can easily count files on Linux .
The easiest way to count files in a directory on Linux is to use the "ls" command. Then, pipe it with the "wc -l".
$ ls | wc -l
As an example, let’s say that you want to count the number of files present in the .
To accomplish this, you would run the "ls" command on the "/etc" directory and pipe it with the "wc" command.
$ ls /etc | wc -l 268
Remark using wc command
An important command resides in the fact that it comes the number of newlines for a given command.
$ ls -l | wc -l 269 $ ls | wc -l 268
If you run "ls" with the "-l" option, you are also printing a line for the total disk allocation for all files in this directory.
In order to count files recursively on Linux, you have to use the "Find" command. Then, you pipe it with the "wc" command to count the number of files.
$ find <directory> -type f | wc -l
The "Find" command is used to search for files on your system.
When you use the "-f" option, you are targeting ony files.
By default, the "Find" command does not stop at the first depth of the directory. It will explore every single subdirectory. This makes file searching recursive.
Count Files using tree
An easy way of compressing files and directory in a directory is to use the "tree" command , and specify the name of the directory to be inspected .
$ tree <directory> 3 directories, 3 files
As you can see, the number of files and directories is available.
If you have a "tree : command not found" or “tree : no such file or directory" you will have to install it using privileges on your system.
$ sudo apt-get install tree (for Ubunbu/Debian hosts) $ sudo yum install tree (for CentOS/RHEL hosts)
Counting hidden files with tree
If you use the "tree" or "ls" commands, hidden files won’t be printed in the terminal output.
To count hidden files using tree, you have to execute "tree" and append the "-a" option for "all" and then go to the directory to be analyzed.
$ tree -a <directory>
You have seen that you can do it using native commands such as the “wc” and “find” commands.