I always use the grep command for this. You can simply run:

grep -o 'word' filename | wc -l

This will count the occurrences of ‘word’ in the file. The -o option in grep makes sure each occurrence is printed on a new line, and wc -l counts these lines. It’s pretty straightforward and works well for me.

We usually combine grep and wc commands to achieve this. If you want to count how many times a word appears in a file, try using:

grep -o -i 'word' filename | wc -l

The -i option makes the search case-insensitive. This method helps us quickly get the count of a specific word, regardless of its case in the file.

If you want to count how many times a word appears, regardless of how many times it’s repeated per line, use:

grep -o 'word' filename | awk 'END {print NR}'

This command will count each occurrence of ‘word’ and awk will print the total number of occurrences. It’s useful for getting an exact count when the word might appear multiple times on a single line.

Read also: How to Delete Lines Starting with a Specific Character in Vim

For a more precise count of a specific word, especially if it’s case-insensitive, you can use:

grep -i -o 'word' filename | grep -v '^$' | wc -l

This method uses grep -i for case-insensitivity and grep -v '^$' to remove any empty lines, ensuring that wc -l counts the exact occurrences of the word.

Categorized in:

Code,

Tagged in: