Bash: Count Number of Files in Directory Matching a Pattern


You can use the following syntax in Bash to count the number of files in a directory that match a particular pattern:

find . -name "*players*" | wc -l

This particular example will return the total number of files in the current directory that contain the string “players” somewhere in the file name.

Here is what the various commands do:

  • find: Used to “find” specific files. We use a period to indicate that the search should be done recursively.
  • -name: Specifies that we want to search file names
  • wc: Stands for “word count” and is used to count items. We use -l to specify that we want to count the number of lines (i.e. number of files) that are found.

The following example shows how to use this syntax in practice.

Example: How to Count Number of Files Matching a Pattern Using Bash

Suppose we would like to count the number of files in our current directory that contain the string “players” in the file name.

First, we can use the following syntax to view all files in our current directory:

ls -R

The following screenshot shows how to use this syntax in practice:

We can then use the following syntax to count the number of files that contain “players” in the file name:

find . -name "*players*" | wc -l

The following screenshot shows how to use this syntax in practice:

Bash count number of files matching pattern

This returns a value of 3, which tells us that there are 3 files in the current directory that contain the string “players” somewhere in the file name.

Note that this also counts the files within the subfolders of the current directory.

Also note that we can use similar syntax to count the total number of files that have a particular extension.

For example, we could use the following syntax to count the number of .txt files in the current directory:

find . -name "*.txt" | wc -l

The following screenshot shows how to use this syntax in practice:

Bash count files with extension pattern in directory

This returns a value of 6, which tells us that there are 6 files in the current directory that have .txt as the file extension.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Count Number of Unique Lines in File
Bash: How to Count Number of Characters in String
Bash: How to Count Number of Columns in File

Leave a Reply