0

To get the count of a string I usually do something a bit hack-ish such as the following:

  1. Do a :%substitution on the string in question, such as:

    # how many times does the string "<Item " occur in the file?
    :%s/\<Item //g
    
  2. Read the output:

    2009 substitutions on 2009 lines
    
  3. Do an undo to go back to the original state of things.

    u


Is there a more straightforward way to get the count of occurrences of a string in vim?

2
  • 2
    Would the function searchcount() work for you? – Mass Feb 9 at 20:13
  • @Mass sure, I've never heard of that before. Want to post a brief answer showing an example and a link to docs for it? – David542 Feb 9 at 21:38
1

The idiomatic answer is

:%substitute/pat//gn

Mass mentions searchcount() which returns a dictionary of interesting items. You'll need to set the last search pattern, though (e.g., / or write to @/), or pass pattern in the options to the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.