How to generate a number sequence in file using vi or Vim?

Sangeeth Saravanaraj picture Sangeeth Saravanaraj · Mar 28, 2012 · Viewed 31.5k times · Source

Is there a way to generate a number sequence in vi or Vim?

For example, for an arbitrary range of lines i  through j (where i < j) in a file opened in Vim, is there a way to generate a number sequence from number 1 on line i all the way through number (j − i + 1) on line j?

Say, I have the following lines in a file:

this is line #1
this is line #2
this is line #3
this is line #4
this is line #5
this is line #6
this is line #7
this is line #8
this is line #9
this is line #10

I want to prefix the number sequence from line 4 to line 8 with numbers 1 through 5. After the operation, the resulting file should be as follows:

this is line #1
this is line #2
this is line #3
1 this is line #4
2 this is line #5
3 this is line #6
4 this is line #7
5 this is line #8
this is line #9
this is line #10

If this is possible, is there a way to use different step sizes for the generated sequence? For example, can 2 be used for the step size instead, so that the resulting sequence is 2, 4, 6, 8, etc.?

Note: The question “How to add line numbers to range of lines in Vim?” brings up a similar problem, but it is not the same.

Answer

kev picture kev · Mar 28, 2012

Select several lines with V(Shift-v), then type command bellow:

:let i=1 | '<,'>g/^/ s//\=i . " "/ | let i+=2

Type :help sub-replace-expression to read more.