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?

6
  • Using your example file and %s/UTg//gn vim gives me here a 56 matches on 4 lines. Commented Apr 7, 2015 at 14:43
  • Hm, which Vim version are you using? I'm using 7.4.663. Commented Apr 7, 2015 at 14:46
  • 7.4.52 on Ubuntu and 7.3 on OSX. Commented Apr 7, 2015 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... Commented Apr 7, 2015 at 15:09
  • 1
    Ah, I once set set gdefault in my ~/.vimrc which enables the /g flag on :s substitutions by default... Commented Apr 7, 2015 at 15:11

1 Answer 1

4

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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.