Which is the Linux command to find number of files in a directory and subdirectories. You can also count number of files in directory recursively in Linux Ubuntu. Let us see how:
Linux Command To Find Number Of Files In A Directory And Subdirectories
Command 1: Use ls and wc command
Command 2: Use tree command
Command 3: Use find command
1. Using ls and wc Commnad
The simplest command to count number of files in a directory and subdirectories is ls and wc command. To use it, simply run:
ls | wc -l
The wc counts the number of bytes, characters, whitespace-separated words, and newlines in each given FILE, or standard input if none are given or
for a FILE. ‘wc’ prints one line of counts for each file, and if the file was given as an argument, it prints the file name following the counts. If more than one FILE is given, ‘wc’ prints a final line containing the cumulative counts, with the file name ‘total’. The counts are printed in this order: newlines, words, characters, bytes, maximum line length.
Whereas the ‘ls’ lists information about files (of any type, including directories).
Note that when we run the command ls and wc with -l options, the command will count all the files and directories but not the hidden ones. To list the hidden files, use -A option with the ls command:
ls -A | wc -l
If you want to count the number of files, including hidden files, in the current directory, run the following set of command:
ls -Ap | grep -v /$ | wc -l
In the above command, -p with ls adds / at the end of the directory names. The -A with ls option will list all the files and directories, including hidden files but excluding . and .. directories. Whereas wc -l counts the number of lines.
Recursively Count Files in Directory
Ubuntu Linux users can use find command to recursively count files in directory:
find DIR_NAME -type f | wc -l
Linux users can also use tree command for displaying the number of files in the present directory and subdirectories:
tree -a
If you want to get the number of files in the current directory only but not the subdirectories, set the level to 1:
tree -a -L 1
Linux Ubuntu users can execute find command to count the number of files in a directory: The find command will get all the files first and then count them using the wc command. Execute the following command:
find directory_path -type f | wc -l
If you don’t want to count the number of files from the subdirectories, limit find command at level 1. Note that level 1 is used for the current directory.
You can execute the following command:
find . -maxdepth 1 -type f | wc -l
For those who are not aware, the ‘find’ command searches the directory tree rooted at each file name. This list of files to search is followed by a list of expressions describing the files we wish to search for.