Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 259
Sangeeth Saravanaraj Avatar asked Mar 28 '12 08:03

Sangeeth Saravanaraj


People also ask

How do I create a numbered list in Vim?

In Vim 8, the first number in a selection can be incremented by pressing Ctrl-A. If the selection covers several lines, the first number in the selection on each line is incremented. Alternatively, numbers in a selection covering several lines can be converted to a sequence by typing g Ctrl-A.


1 Answers

Starting with Vim 7.4.754 one can use g Ctrl-a, see :help v_g_CTRL-A

Go to line #4, use Ctrl-v to blockwise select the first character, go down 4 lines, press Shift i, enter 0 (this is 0, followed by Space) and Esc to exit insert mode.

Now use gv to re-select the previously selected area. Press g Ctrl-a to create a sequence.

I start with a 0 here, so I can re-select by gv. If you start with a 1, you need to re-select by hand while omitting the first 1.

Use 2g Ctrl-a to use a step count of 2.


screen capture demonstrating how to generate a number sequence

like image 169
rkta Avatar answered Sep 22 '22 01:09

rkta