Reputation: 793
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
Upvotes: 56
Views: 27701
Reputation: 24077
Nowadays (as of 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.
Relevant 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 the google/vim-searchindex plugin, which works for any amount of results:
(By default the plugin is limited to files with “only” less than one million lines; this can be adjusted with let g:searchindex_line_limit=2000000
.)
Upvotes: 60
Reputation: 13058
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
Upvotes: 58
Reputation: 459
Use the following commands.
:%s/pattern//ng
g
stands for global, it will match multiple occurrences per line.
Outputs are shown as
13 matches on 10 lines
:%s/pattern//n
Outputs are shown as
10 matches on 10 lines
Upvotes: 3
Reputation: 172648
My SearchPosition plugin would print the following output (with the cursor on the first match, and the <A-m>
mapping or :SearchPosition name
command):
On sole match in this line, 2 in following lines within 5,13 for /\<name\>/
It builds on the other solutions given here, and was expressly written for obtaining such statistics easily.
Upvotes: 0
Reputation: 11820
I have a count word function that you cand use in a number of ways
fun! CountWordFunction()
try
let l:win_view = winsaveview()
exec "%s/" . expand("<cword>") . "//gn"
finally
call winrestview(l:win_view)
endtry
endfun
command! -nargs=0 CountWord :call CountWordFunction()
So, you can map it:
nnoremap <F3> :CountWord<CR>
Even mouse double click...
" When double click a word vim will hightlight all other ocurences
" see CountWordFunction()
" [I shows lines with word under the cursor
nnoremap <silent> <2-LeftMouse> :let @/='\V\<'.escape(expand('<cword>'), '\').'\>'<cr>:set hls<cr>:CountWord<cr>
nnoremap <Leader>* :let @/='\V\<'.escape(expand('<cword>'), '\').'\>'<cr>:set hls<cr>:CountWord<cr>
Upvotes: 1