Count Number of Occurrences of a Word in a File in Linux

Count Number of Occurrences of a Word in a File in Linux

In Linux, there are various commands to work with text files processing. Sometimes we may need to count number of occurrences of a word in a file in Linux. This tutorial shows how to do that.

The grep command can be used for searching specific word in a file. The output of grep command can be passed to wc command to count the occurrences of a word. For example, the following command counts occurrences of word localhost in /etc/hosts file:

grep -o "localhost" /etc/hosts | wc -l

The -o option instructs to output each corresponding match in a separate line.

In order to perform case-insensitive search, add -i option:

grep -o -i "localhost" /etc/hosts | wc -l

Leave a Comment

Cancel reply

Your email address will not be published.