Artur
Artur

Reputation: 793

How to count search results in Vim?

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

Answers (5)

ruohola
ruohola

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.

native search count

Relevant section from the Vim help

Note that if the search finds more than 99 results, Vim unfortunately just shows [x/>99]:

native search count over 99

For this reason, I personally use the google/vim-searchindex plugin, which works for any amount of results:

vim-search-index search count

(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

agnul
agnul

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

KittoMi
KittoMi

Reputation: 459

Use the following commands.

  1. Multiple matches per line
:%s/pattern//ng

g stands for global, it will match multiple occurrences per line.

Outputs are shown as

13 matches on 10 lines
  1. Line matches
:%s/pattern//n

Outputs are shown as

10 matches on 10 lines

Upvotes: 3

Ingo Karkat
Ingo Karkat

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

SergioAraujo
SergioAraujo

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

Related Questions