How do you know how many files are there is a directory?
In this quick tutorial, you'll learn various ways to count the number of files in a directory in Linux.
Method 1: Use ls and wc command for counting number of lines in directory
The simplest and the most obvious option is to use the wc command for counting number of files.
ls | wc -l
The above command will count all the files and directories but not the hidden ones. You can use
-A option with the ls command to list hidden files but leaving out . and .. directories:
ls -A | wc -l
If you only want to count number of files, including hidden files, in the current directory, you can combine a few commands like this:
ls -Ap | grep -v /$ | wc -l
Let me explain what it does:
-pwith ls adds
/at the end of the directory names.
-Awith ls lists all the files and directories, including hidden files but excluding . and .. directories.
grep -v /$only shows the lines that do NOT match (
-voption) lines that end with
wc -lcounts the number of lines.
Basically, you use
ls to list display all the files and directories (with / added to directory names). You then use pipe redirection to parse this output to the grep command. The grep command only displays the lines that do not have / at the end. The wc command then counts all such lines.
Method 2: Use tree command for counting number of files in directory
You can use the tree command for displaying the number of files in the present directory and all of its subdirectories.
As you can see, the last line of the output shows the number of directories and files, including the hidden ones thanks to option
If you want to get the number of files in current directory only, exclude the subdirectories, you can set the level to 1 like this:
tree -a -L 1
Method 3: Use find command to count number of files in a directory
The evergreen find command is quite useful when it comes with dealing with files.
If you want to count the number of files in a directory, use the find command to get all the files first and then count it using the wc command.
find directory_path -type f | wc -l
-type f you tell the find command to only look for files.
If you don't want the files from the subdirectories, limit the scope of find command at level 1, i.e. current directory.
find . -maxdepth 1 -type f | wc -l
There could be some other ways to count the number of lines in a directory in Linux. It's up to you how you want to go about.
I hope you find this helpful. Feel free to leave a question or suggestion in the comment section.