Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 5 down vote accepted

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
share|improve this answer
    
Thank you. Impressive! –  brauner Mar 18 at 13:52

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
share|improve this answer
    
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. –  brauner Mar 18 at 11:03
    
@brauner I see. I'm afraid you'll need to wait for a vim guru for this. –  Joseph R. Mar 18 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. –  brauner Mar 18 at 11:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.