How to Count Word Occurrences in a Text File?

Graphical User Interface word processors and note-taking applications have information or detail indicators for document details such as the count of pages, words, and characters, a headings list in word processors, a table of content in some markdown editors, etc. and finding the occurrence of words or phrases are as easy as hitting  Ctrl + F and typing in the characters you want to search for.

 

A GUI does make everything easy but what happens when you can only work from the command line and you want to check the number of times a word, phrase, or character occurs in a text file? It’s almost as easy as it is when using a GUI as long as you’ve got the right command and I’m about to narrate to you how it is done.

 

Suppose you have an example.txt file containing the sentences:

Hello World. How are you? How old are you? How long will it take?

 

You can use grep command to count the number of times "mauris" appears in the file as shown.

$ grep -o -i how example.txt | wc -l

 

Using grep -c alone will count the number of lines that contain the matching word instead of the number of total matches. The -o option is what tells grep to output each match in a unique line and then wc -l tells wc to count the number of lines. This is how the total number of matching words is deduced.

 

A different approach is to transform the content of the input file with tr command so that all words are in a single line and then use grep -c to count that match count.

$ tr '[:space:]' '[\n*]' < example.txt | grep -i -c how

 

Was this answer helpful? 0 Users Found This Useful (0 Votes)