Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count search results in Vim?

Tags:

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

like image 340
Artur Avatar asked Mar 15 '18 10:03

Artur


People also ask

How do I count occurrences in Vim?

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.

How do I count specific words in Vim?

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.

What is G in Vim?

: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).


2 Answers

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

like image 155
agnul Avatar answered Oct 05 '22 22:10

agnul


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.

native search count

Relavant 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 google/vim-searchindex, which works for any amount of results:

vim-search-index search count

(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.)

like image 28
ruohola Avatar answered Oct 05 '22 23:10

ruohola