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?
%s/UTg//gnvim gives me here a56 matches on 4 lines.7.4.663.7.4.52on Ubuntu and7.3on OSX.~/.vimrcmight be the culprit. If I leave out thegin%s/UTg//gnand only use%s/UTg//nVim will output the correct count...set gdefaultin my~/.vimrcwhich enables the/gflag on:ssubstitutions by default...