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
:4,8s/^/\=line(".")-3." "
will do what you want
if you need count=2:
:4,8s/^/\=2*(line(".")-3)." "
this will give you 2,4,6,8,10
line numbers are hard coded in my example, you could use V to select those lines you want to change.
(if your vim has Perl support -- default in many Linux Distributions): Select the lines in visual mode (V) and do
:perldo s/^/++$z . " "/e
or
:4,8 perldo s/^/++$z . " "/e
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:
qq
: record macro into register q
0
: go to first column.yf
: yank all until and including the first space (remember your first line has 1
and a space).0jP
: go down and paste the pattern at the start of the line.0<C-a>
: go to first column and increment number by one.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.
Select the target lines in Visual mode, then run the Ex command
:'<,'>s/^/\=(line('.')-line("'<")+1).' '
A less flexible, but an easy to remember method is to use a renumbering plugin like Renumber.vim http://www.vim.org/scripts/script.php?script_id=189
If there aren't any numbers yet, like in the OP, some number should be inserted in their place. Renumber can handle the actual ordering and it does it based on just the first number.
In this example I'm using <C-v>
to insert the starting number on all the lines you want numbered.
4G<C-v>4jGI1 <Esc>gv:Renumber
To use steps of two
:Renumber s2
I think all the proposed solutions are too difficult to remember, you can use it once but then you need to go into all details every time you use it (if you use it less than once a day or so).
I found the visual incrementing script really easy to install and use. Once it is installed in vim, you just need to generate a column of 0's, select it with Ctrl-V and write the command :I. It will then automatically generate increasing numbers on each line. There are also other features:
This solves a more general problem because it works also at a position different from column 0, the column has just to be selectable with Ctrl-V.
The vimball of the plugin is here or here.