Counting All Files in a Linux Directory

To count how many files there are in a directory using the terminal on a Linux machine you can combine 2 commands:

  • find
  • wc

We’ll use the find command to locate all the files (and exclude directories and other non-files) and then the wc command to count the files.

Find has many options, but we will only be using the type option:
find . -type f

The . indicates the directory to search in and can be replaced with any absolute or relative path. This command will also find files in subdirectories. To exclude subdirectories you can use:

find . ! -name . -prune -type f

The ! -name . -prune will ignore any directories that are not the current one.

The find command will give us a list of all the files we want to count, to count the number of entries in that list we must pass the output to wc to count it.

By default, wc will count words, newlines, and bytes. Since the output from find is a list of files, each separated by a newline, we can tell wc to only count newlines by using the -l argument: wc -l
Combining this into a single command, we get the final command to find count the number of files in a directory excluding sub-directories:
find . ! -name . -prune -type f | wc -l

(Of course, if you want to include sub-directories, simply remove the ! -name . -prune arguments and use:
find . -type f | wc -l instead)

Tags: , ,

Leave a Reply