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

Solution 1:

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

Solution 2:

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.

Solution 3:

Instead of a complicated construct you could simply use a macro with the CTRL-a function to increment a leading number. Example data:

aaa
bbb
ccc

first insert a start number and a space:

1 aaa
bbb
ccc

then record this macro on line 1 (<C-a> means press CTRL-a):

qq0yf 0j0P0<C-a>q

Explanation:

  1. qq: record macro into register q
  2. 0: go to first column.
  3. yf: yank all until and including the first space (remember your first line has 1 and a space).
  4. 0jP: go down and paste the pattern at the start of the line.
  5. 0<C-a>: go to first column and increment number by one.
  6. q: end macro recording.

this gives:

1 aaa
2 bbb
ccc

now you can apply this macro using @q as long as you want. If you need an increase of two just use CTRL-aCTRL-a instead of just once. Now you could apply this macro to consecutive lines, for example:

:.,$norm @q

will add leading line numbers for the rest of your file.