How to Count the Number of Files in a Directory in Linux

642

Below are list of commands from which you will able to find various files counts: e.g. How many files are there recursively in a folder?, Find all files in this directory, including the files in sub-directories?

1. Count Number of Files in the Current Directory

To determine how many files there are in the current directory. Using Linux command, we can get the number of files in the current directory.

ls -1 | wc -l

(Alternate command using find: find . -maxdepth 1 -type f| wc -l)

2. Count files recursively in a directory using Linux

Below command will find Number of Files in a Directory and all Subdirectories

find DIR_NAME -type f | wc -l

Explanation:

  • -type f to include only files.
  • | (and not ¦) redirects find command’s standard output to wc command’s standard input.
  • wc (short for word count) counts newlines, words and bytes on its input (docs).
  • -l to count just newlines.

Above command counts the number of files recursively in the current and all directories

Approach-2

If you want a breakdown of how many files are in each directory under your current directory:

for i in $(find . -maxdepth 1 -type d) ; do 
    echo -n $i": " ; 
    (find $i -type f | wc -l) ; 
done

3. Count total number of files in particular directory with specific extension

If you want to count the total number of files in particular directory that ends with particular extension.

ls -lR /path/to/dir/*.jpg | wc -l

Above command will give you count of file with “jpg” extension

 

Facebook Comments