0

I try to count all occurrences of a char or word in a file with Vim. This means multiple occurrences of the same word in the same line should be taken into account as well. This has been discussed in several posts before: Counting occurrences in Vim without marking the buffer changed, Search for string and get count in vi editor, Is there a way to count the number of matches in Vim using :g?. My default strategy was to use:

%s/PATTERN//gn

for chars and

%s/\<PATTERN\>//gn

for words. This is mentioned in the Vim help page. However, it seems that both solutions ignore multiple occurrences in the same line. Here is an example:

UTg    UTg    D1U1K1    UTg    D1U1K2    UTg    D1U1TW01    UTg    D1U1TW02    UTg    D1U1TW03    UTg    D1U1TW04    UTg    D1U1TW05    UTg    D1U1TW06    UTg    D1U1TW07    UTg    D1U1TW08    UTg    D1U1TW09    UTg    D1U1TW10    UTg
UTg    UTg    D1U2K1    UTg    D1U2K2    UTg    D1U2TW01    UTg    D1U2TW02    UTg    D1U2TW03    UTg    D1U2TW04    UTg    D1U2TW05    UTg    D1U2TW06    UTg    D1U2TW07    UTg    D1U2TW08    UTg    D1U2TW09    UTg    D1U2TW10    UTg
UTg    UTg    D1U3K1    UTg    D1U3K2    UTg    D1U3TW01    UTg    D1U3TW02    UTg    D1U3TW03    UTg    D1U3TW04    UTg    D1U3TW05    UTg    D1U3TW06    UTg    D1U3TW07    UTg    D1U3TW08    UTg    D1U3TW09    UTg    D1U3TW10    UTg
UTg    UTg    D1U4K1    UTg    D1U4K2    UTg    D1U4TW01    UTg    D1U4TW02    UTg    D1U4TW03    UTg    D1U4TW04    UTg    D1U4TW05    UTg    D1U4TW06    UTg    D1U4TW07    UTg    D1U4TW08    UTg    D1U4TW09    UTg    D1U4TW10    UTg

when using %s/UTg//gn it will output 4 instead of 56. So how can I count all occurrences including multiple occurrences in the same line in Vim?

  • Using your example file and %s/UTg//gn vim gives me here a 56 matches on 4 lines. – FloHimself Apr 7 '15 at 14:43
  • Hm, which Vim version are you using? I'm using 7.4.663. – lord.garbage Apr 7 '15 at 14:46
  • 7.4.52 on Ubuntu and 7.3 on OSX. – FloHimself Apr 7 '15 at 14:50
  • That can't be it, I checked both version. Some setting in my ~/.vimrc might be the culprit. If I leave out the g in %s/UTg//gn and only use %s/UTg//n Vim will output the correct count... – lord.garbage Apr 7 '15 at 15:09
  • 1
    Ah, I once set set gdefault in my ~/.vimrc which enables the /g flag on :s substitutions by default... – lord.garbage Apr 7 '15 at 15:11
2

It is possible to enable the /g flag on :s substitutions by default by setting

set gdefault

in .vimrc. If this is set using

:%s/PATTERN/gn

will cause Vim to count occurrences of chars or words once per line and ignore all other occurrences. Either use

:%s/PATTERN/n

in this case or remove set gdefault from .vimrc.

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.