Count Word Occurences in File in Linux

Last updated on Dec 29, 2019 in Linux

When you need to count word occurences in a text file, you have at least two options: open the file in your favorite text editor and use its built-in tools, or do it directly from the terminal using some basic Linux commands such grep and wc.

In this example, we have a text file which content is (we use cat only for the demonstration):

$ cat myfile.txt
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis convallis volutpat nulla ut tempor. Aliquam a urna condimentum, posuere augue non, posuere ante. Praesent tellus ex, condimentum id felis vitae, semper dapibus arcu. Donec tristique tincidunt turpis a pharetra. Vivamus sed ultricies libero. Aliquam erat volutpat. Nam convallis nec quam sit amet tincidunt. Fusce commodo lobortis congue. In dapibus augue sit amet metus volutpat, ut finibus dui pellentesque. Curabitur lacinia tortor non mollis condimentum. Curabitur dolor tellus, aliquet eget diam vel, placerat scelerisque ex. Vestibulum et sem dapibus, egestas odio a, egestas orci. Nam vestibulum vel metus sed tempus. Donec nec arcu eu nisi consectetur mattis eget eget libero.

To count how many times the word ex is found in the text, type:

$ grep -o ex myfile.txt
  • -o tells grep to echo found occurences only, not the full line, which is the default
  • ex this is our search term

In the output we can see two lines of ex, which means that it was found two times. Now it is easy to count the lines with wc:

$ grep -o ex myfile.txt | wc -l

The result is 2. To read more about counting lines, you can read Count Lines in File in Linux