When editing text files, you might want to know the total number of words in the document. Sometimes you would want to count the number of a specific word. If you are using the vim or vi editor, then you can easily count the words using one of the following commands.
count total number of words
If you want to count the total number of words in the entire file, then first hit g and followed by Ctrl-g. This will print out information about the file such as the lines, words and bytes. You will see something like this:
Col 1 of 6; Line 1 of 30; Word 4 of 92; Byte 45 of 2567
count number of specific words
Some times you want to count the occurrence of a specific word in the file. In order to do that, use the following command.
n is the command to count and g specifies to match all occurrence in a line. So the above command will print out something like
7 matches on 6 lines.
To count only a certain part of the buffer or file, use the line numbers instead of the ‘%’ (which means all lines), so to search between lines 123 and 888 the above will look something like:
count number of matching words
Some times you want to count the occurrence of several words or words that match a certain pattern. You can use the same command that you used to match the word, but this time with a regular expression.
This will match all the words that are 4 character long and starts with ‘ba’ and ends with an ‘e’.