How to Use awk to Count Number of Occurrences of Word


Often you may want to use awk to count the number of occurrences of specific words in a column of a file.

You can use the following methods to do so:

Method 1: Count Occurrences of Specific Word in Column

awk '($2=="Guard") {count++ } END { print count }' athlete_data.txt

This particular example will count the number of occurrences of the word “Guard” in column 2 of the file named athlete_data.txt.

Method 2: Count Occurrences of All Unique Words in Column

awk '{count[$2]++} END {for(i in count) print i, count[i]}' athlete_data.txt

This particular example will count the number of occurrences of all unique words in column 2 of the file named athlete_data.txt.

The following example shows how to use each of these methods in practice with the following file named athlete_data.txt that contains information about various basketball players:

Example 1: Use awk to Count Occurrences of Specific Word in Column

Suppose that we would like to count the number of occurrences of the word “Guard” in column 2 of the file.

We can use the following syntax to do so:

awk '($2=="Guard") {count++ } END { print count }' athlete_data.txt

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

awk count occurrences of word in column

From the output we can see that the word “Guard” occurs a total of 5 times in column 2 of the file.

Example 2: Use awk to Count Occurrences of All Unique Words in Column

Suppose that we would like to count the number of occurrences of each unique word in column 2 of the file.

We can use the following syntax to do so:

awk '{count[$2]++} END {for(i in count) print i, count[i]}' athlete_data.txt

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

awk count occurrences of each unique word in file

From the output we can see:

  • The word “Center” occurs 1 time in column 2.
  • The word “Forward” occurs 2 times in column 2.
  • The word “Guard” occurs 5 times in column 2.

Feel free to replace $2 in the code to count the number of occurrences of each unique word in a different column of the file.

Related Tutorials

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

How to Use awk to Print All Columns After Specific Number
How to Use awk to Print Rows Where Column Equals Value
How to Use awk to Print Last Line of a File
How to Use awk to Print a Range of Columns

Leave a Reply