How to Count Word Occurrences in a Text File using Shell Script?


Linux shell scripting has many powerful tools to process the data in files. One such feature is to find patterns and count the number of occurrences of matched patterns. One such example is to count the number of occurrences of a specific word in a given file. This is achieved by combination of commands for pattern search and counting. Below are the approaches which can be used for this need.

Input file

Lets use the below file for demonstrating the examples.

$ cat inspire.txt
Mastering anything needs practice.
It also needs patience.
And it needs time and other resources.

Using grep and wc

The grep command finds the pattern but it has some switches which can be used to print the pattern in new line every time it finds it. That is –o option. Also we can use the -i switch for ignoring the case of the word found. Finally, the result can be pipelined to wc to get the final count.In this example we count the number of occurrences of the word “needs”.

Approach

We grep for the word “needs” in the file. Use the –o switch to get each of the output as a new line. Use –i to ignore the case. Then pipeline it to wc in order to get the number of lines which is ultimately the number of occurrences of the word.

$ grep -o -i needs inspire.txt | wc -l

Running the above code gives us the following result −

3

Using tr command

The tr command translates one string to another. So we translate all the spaces into a new line and then grep for the pattern. Finally count the number of occurrences of the specific word by using the -c switch of grep for count and -i switch for ignoring the uppercase/lowercase word.

tr '[:space:]' '[
*]' < inspire.txt | grep -i -c it

Running the above code gives us the following result −

2

Updated on: 03-Jan-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements