Search code examples
vimcountcharacteratom-editorvi

How to count how many specific characters before cursor on the current line using vim?


In vim, would it be possible to count the number of a specific pattern before the current cursor position?

foo1*foo2*foo3*foo4*foo5,...
bar1*bar2*bar3*[cursor]bar4*bar5,...

If [cursor] is where I'm interested in, is there any way I can quickly count the number of asterix before this on this particular line (line 2), in which case the result should be 3. This way I know the position of this N is 4.

In a file with fooN and barN where N is big, I would like a fast & simple way to determine the position of this (and of course, the actual data doesn't have N).


Solution

  • :echo count(getline('.')[0:getpos('.')[2]-1], '*')