Here are the best ways of finding and counting the number of files or folders in a particular directory.
Count the number of files in a current directory
Using “ls” command:
This method is the best, if you need to count a large number of files.
$ ls -f . | wc -l
This command also enables -a
option, so .
, ..
and other files starting with .
, will be counted.
Using “find” command:
$ find . -type f -maxdepth 1 | wc -l
Count the number of files recursively
The following command recursively counts the number of files in a current directory and all its sub-directories:
$ find . -type f | wc -l
Count the number of folders recursively
The following command recursively counts the number of folders in a current directory and all its sub-directories:
$ find . -type d | wc -l
Count the number of files by “file type”
The following command recursively counts the number of files, with “.txt” extension, in a current directory and all its sub-directories:
$ find . -type f -name "*.txt" | wc -l
Need to have the count of the file older than 10 days altering below command
$ find . -type f -name “*.txt” | wc -l
ls /dir/*.ext | wc -l with a large number of files (tenthousands) Returns 0 or error.
This is not be the best solution!