Is it possible to count how many times a word or a pattern appears in a file? This is sometimes useful to find out how many times a function has been called, etc.
Quincy's answer is fine, but there's an exact way to do this which doesn't require editing the buffer:
This will print a message like
3 matches on 2 lines, and no changes will be made to your buffer.
n flag makes the
:substitute command print the number of matches instead of performing an actual substitution; the
g flag enables reporting of multiple matches per line.
Another thing that might be useful to your use case is to print all lines that match a pattern:
which can be shortened to:
This is one of the simplest uses of the
:global command (which is mind-bogglingly powerful). It will simply print out all of the lines that match
pattern, and then (if there is more than one line) you press
Enter or type another command to make it go away.
A bit of trivia: This command is the origin of the name
grep, as it would commonly be described as
re stands for "regular expression".
Thanks to this PR https://github.com/vim/vim/pull/4317 , each search command shows search statistics (like current match position, and number of matches) in vim 8.1.1270. Make sure to remove
S from the variable
Nowdays you can use:
to enable a count of
[x/y] showing in the bottom right corner every time you do a
A mapping I added to my .vimrc based on the answers here:
" count nr of occurrences of word under cursor nnoremap <leader>c :%s/<c-r><c-w>//gn<cr> " count nr of occurrences of visual selection vnoremap <leader>c :<c-u>%s/<c-r>*//gn<cr>
A bit of explanation, hopefully helpful for newer vimmers:
<c-r><c-w>inserts the word under the cursor in the command line, handy in many occasions.
<c-u>is needed to remove the automatically inserted
:in visual mode and going to the command line. The
*register contains the (last) visual selection,
<c-r>*inserts the contents of the
*register in the command line (can also be used in insert mode).