Wednesday 9 October 2013

vim substitution tricks

I wanted to figure out a way to add an incrementing number before a certain character on each line for a program I was writing.
In vim this is fairly simple to achieve.

Here is a sample of some lines in my file
number=1234
number=4543
number=7978
number=3321

Now I want to add an incrementing number before the "=" so I have some unique variables. I can either select the lines I want in vim using the visual selection (shift-v) or I can put an address specification.
For this example I used the visual selection so I get and address specified as '<,'>

Now I supply the ex command
:let i=1 | '<,'>s/=/\=i."="/ | let i+=1

This will now give me
number1=1234
number2=4543
number3=7978
number4=3321

This seemed to work the same as the following command but less typing
:let i=1 | '<,>'g/=/s//\=i."="/ | let i+=1

However if I wish to change the increment I have to use the long command, e.g. to go up in steps of two, change the ex command to
:let i=1 | '<,>'g/=/s//\=i."="/ | let i+=2

Which now gives me
number1=1234
number3=4543
number5=7978
number7=3321

The string to replace in the search and replace pattern above starts with "\=" indicating that this is the start of an expression, subsequent strings are concatenated with ".".