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

前端 未结 10 2038
野趣味
野趣味 2020-12-07 09:47

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

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 10:23

    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 ( means press CTRL-a):

    qq0yf 0j0P0q
    

    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: 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.

提交回复
热议问题