Use grep to Count All Occurrences of String per File


Often you may want to use the grep command in Bash to count all occurrences of a specific string in each file in a directory.

You can use the following methods to do so:

Method 1: Count Occurrences of String in Each File

grep -c "Mavs" *

This particular example will return the number of occurrences of the string “Mavs” in each individual file in the current directory.

Method 2: Count Occurrences of String in All Files

grep -o "Mavs" * | wc -l

This particular example will return the total number of occurrences of the string “Mavs” across all files in the current directory.

The following example shows how to use each of these methods in practice.

Example: Use grep to Count All Occurrences of String per File

Suppose that our current directory has the following three files in it:

  • team_info1.txt
  • team_info2.txt
  • team_info3.txt

We can use the cat command to view the contents of each of these files:

Each file contains information about the total points scored by basketball players on various teams.

Suppose that we would like to count the total occurrences of the string “Mavs” in each file.

We can use the following syntax to do so:

grep -c "Mavs" *

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

grep count occurrences of string per file

From the output we can see:

  • The file team_info1.txt contains 1 occurrence of the pattern “Mavs”
  • The file team_info2.txt contains 2 occurrences of the pattern “Mavs”
  • The file team_info3.txt contains 0 occurrences of the pattern “Mavs”

Now suppose that we would like to count the number of occurrences of the pattern “Mavs” across all files in the current directory.

We can use the following syntax to do so:

grep -o "Mavs" * | wc -l

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

grep count total occurrences of string in all files

This returns the value 3, which tells us that the pattern “Mavs” occurs a total of 3 times across all files in the current directory

Related Tutorials

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

How to Use grep to Get Line Number of Match
How to Use grep to Extract Last Occurrence in File
How to Use grep with Case-Insensitive Matching
How to Use grep to List All Files Containing Specific String

Leave a Reply