In this tutorial, you will learn how to count the files in a directory by using the ls
and find
commands on Linux. Some examples will also show how to count hidden files, count files in all subdirectories, or how to count directories plus files.
Using ls Command
Example 1. You can count files by using the ls
command in conjunction with the wc
command. The -1
option of ls
will list one file per line, and the -l
option of wc
will count the number of lines.
$ ls -1 | wc -l
Example 2. Or to count the files in some other directory:
$ ls -1 /path/to/dir | wc -l
Example 3. To include hidden files in the count, add the -A
option to your ls
command:
$ ls -1A | wc -l
Using find Command
Example 1. The find
command is for searching files and directories. This example will count the number of files in the current directory, as well as all subdirectories. Note that this example will count files only, NOT directories. It will also count hidden files.
$ find . -type f | wc -l
Example 2. Or to count the number of files in a different directory:
$ find /path/to/dir -type f | wc -l
Example 3. If you don’t want to include the files from subdirectories, you can use the -maxdepth
option.
$ find . -maxdepth 1 -type f | wc -l
Example 4. By using !
, you can avoid counting hidden files (those beginning with .
) in the current directory and subdirectories.
$ find . -type f ! -name ".*" | wc -l