Paste block multiple times with (increasing) numbering using vim

Viewed 175

I have a block in a yaml file that I would like to yank and paste several times:

- probeNumber: 1
  probeLocation: [0, 0, 0.1]

Is it possible to automatically increment the value of probeNumber and probeLocation in each block? Like so:

- probeNumber: 1
  probeLocation: [0, 0, 0.1]

- probeNumber: 2
  probeLocation: [0, 0, 0.15]

- probeNumber: 3
  probeLocation: [0, 0, 0.20]

probeLocation is not an integer, it is incremented by a fixed value in each block (0.05). I need 1000 or so of these blocks so doing this manually is not feasible.

2 Answers

Create a template in your text file, suppose starting with line 1.

- probeNumber: 1
  probeLocation: [0, 0, 0.1]

- probeNumber: 1
  probeLocation: [0, 0, 0.1]

...repeat the number as you want, e.g. copy the first block and do 100p for 100 copy

Then use following command to update the value:
For updating probeNumber

:%s!1$!\=printf("%d", line('.')/3+1)!g

For updating probeLocation

:%s!0\.1!\=printf("%0.2f", 0.10+(line('.')/3)*0.05)!g

Where 0.10 is the initial value, 0.05 is the increment.

Thank for SergioAraujo pointing out mistake of the original expression
:%s!0\.1$!\=printf("0.%d", 10+(line('.')/3)*5)!g
Which fails as the replaced value will never be greater than 1.

The main idea is to use line function to update the value, you may check Replace a pattern with current line number and Insert line numbers for more details.

I have figured out another way of solving this issue:

If you have the three first lines on the clipboard, which means the two first lines and a blank line you could create the file with this:

:for i in range(999) | silent! 0put + | endfor

In order to increase probeNumber lines:

:let c=1 | g/\d\+$/ s//\=c/ | let c+=1

Now the lines with probeLocation:

:let c=0.10 | g/0\.1\ze]/ s//\=printf("%0.2f", c)/ | let c+=0.05
Related