How to find in the text file using Vim how many times specific word repeats.
For example, I want to see how many times word "name" repeats in the code:
"collection": "animals", "fields": [ { "field": "id", "name": "" }, { "field": "age", "name": "" }, { "field": "origin", "name": "" }
Result - 3
This makes it easy to count the number of occurrences of the word under the cursor: first press * to search for the current word, then enter :%s///gn to count all occurrences of that word.
To count the number of words in the current buffer, press g then Ctrl-g. To count the number of words in a block, select the block (for example, type V5j to select 6 lines) and again press g then Ctrl-g.
:g/pattern/cmd :range g/pattern/cmd. The g command first scans all lines in range and marks those that match pattern . It then iterates over the marked lines and executes cmd . (See multi-repeat in vim's documentation).
You can count the number of matches using the n
flag in the substitute command. Use the following to show number of times that some-word
matches text in current buffer:
:%s/some-word//gn
You can read all the details on the vim tips wiki
Nowdays (meaning Vim 8.1.1270) you can use:
set shortmess-=S
to enable a count of [x/y]
showing in the bottom right corner every time you do a /
or ?
search.
Relavant section from the Vim help
Note that if the search finds more than 99 results, Vim unfortunately just shows [x/>99]
:
For this reason, I personally use google/vim-searchindex, which works for any amount of results:
(By default the plugin is limited to files with "only" less than 100k lines, this can be adjusted with let g:searchindex_line_limit=1000000
though.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With