How To Count The Number Of Files In A Directory On Linux

How to count the number of files in a directory recursively on Linux Ubuntu. On Unix, count files in directory and subdirectories or number of files in a directory in Linux

1st Command: Count Files In A Directory Using Wc Command

The ‘wc’ counts the number of bytes, characters, whitespace-separated words, and newlines in each given FILE.

When a file name is 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’.

NOTE: The counts are printed in this order:

  1. newlines
  2. words
  3. characters
  4. bytes
  5. maximum line length

Each count is printed right-justified in a field with at least one space between fields so that the numbers and file names normally line up nicely in columns.

The easiest way to to count files in a directory is using wc command together with ls command as:

ls -1 | wc -l

NOTE: When the directory has more than 100 of files in it, using the regular wc command will take a large amount of time to execute. Soi nstead use the following command:

ls -f | wc -l

2nd Command: Count Files In A Directory Using Find Command

The find command can be used to count files in a directory recursively.

Which means, using the find command will count and display the number of files in a certain directory and within the directories. The command will have the following syntax:

find DIRECTORYNAME -type f | wc -l

3rd Command: Count Files In A Directory Using egrep Command

egrep command is similar to wc command. The egrep command displays the number of files in the current directory.

You can use the egrep command as:

ls -l . | egrep -c '^-'

Apart from the above three commands you can also use the tree command to count files and directories. The tree command returns a list of all the files and directories in a directory with their hierarchy.

Original Article