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.
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
grep -o "localhost" /etc/hosts | wc -l
-o option instructs to output each corresponding match in a separate line.
In order to perform case-insensitive search, add
grep -o -i "localhost" /etc/hosts | wc -l