2

I am trying to use a for loop iterator variable in a vim search pattern to determine for a range of words how man times they occur in a file. What I do so far is:

for i in range(1,40) | %s/SiTg//gn | endfor

I need the iterator variable i in the search pattern %s/S\iTg//gn to be bound by the for loop. How can I achieve this in vim?

3 Answers 3

8

Vimscript is evaluated exactly like the Ex commands typed in the : command-line. There were no variables in ex, so there's no way to specify them. When typing a command interactively, you'd probably use <C-R>= to insert variable contents:

:sleep <C-R>=timetowait<CR>m<CR>

... but in a script, :execute must be used. All the literal parts of the Ex command must be quoted (single or double quotes), and then concatenated with the variables:

execute 'sleep' timetowait . 'm'

In your example, you want to place the i variable into the :%s command:

for i in range(1,40) | execute '%s/S' . i . 'Tg//gn' | endfor
0
0

If you're not using the for loop for other purposes, you can always expand your regex to cover the whole range of numbers:

:%s/S\([1-4]0\|[1-3]*[1-9]\)Tg//gn
3
  • Cheers. I need the for loop to consecutively show me for each specific word how many matches there were. E.g. S1Tg four times, S2Tg four times, S3Tg four times etc. Mar 18, 2015 at 11:03
  • @brauner I see. I'm afraid you'll need to wait for a vim guru for this.
    – Joseph R.
    Mar 18, 2015 at 11:09
  • Yeah, I'm looking for a pure vim solution. With a for loop and grep it's quite easy: for I in {1..40}; do grep -c "S${I}Tg" FILE; done. Mar 18, 2015 at 11:13
0

You can use the \=<subexpression> modifier, e.g.: :s/a/\=g:integer."a"/g ← it'll prepend all letters a with the g:integer's value.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .