To assign numbers in ascending order when replacing the same number

Asked 2 years ago, Updated 2 years ago, 85 views

For example, suppose you have the following files:

0,foo
0,bar
0, hoge
0, fuga

For this first number (in this case, 0), I would like to assign an ascending number instead.To be more specific, I would like the following text:

1,foo
2,bar
3, hoge
4, fuga

As expected, editing little by little by hand seems inefficient.If there is a good way, please let me know.

vim

2022-09-30 21:13

3 Answers

For Vim 7.4.765 or later, g<C-a> after selecting the target in visual mode generates a serial number.


2022-09-30 21:13

Just in case, I'll write down other methods.

Number == line number is acceptable:

:%s/^\d\+/\=line(".")


If you want to start over from 1 in the selected range in visual mode:
(Shift+v and press : to automatically enter :'<,'>)

: '<, '>s/^\d\+/\=line(".")-line("'<")+1


2022-09-30 21:13

It's a little complicated, but it's a macro version.

<CTRL-A>:%s/^0//
ggqqyw+P<CTRL-A>0q2@q
  • <CTRL-A>
    • Add to 0 on the first line
    • 10<CTRL-A>
    • if you want to jump 10
  • :%s/^0//
    • Clear the rest of the line 0
  • ggqyw+P<CTRL-A>0q
    • Return to the beginning of the statement (gg) Start recording to register q (qq)
    • Yank words (yw) Go to the beginning of the next line (+) Paste to the left of the cursor (P)
    • Add (<C-A>) to the cursor position number (pasted previous line number)
    • Back to line beginning (0)
    • End Recording (q)
  • 2@q
    • Specify the number of iterations and run the macro in register q with @q
  • Add to 0 on the first line
  • 10<CTRL-A>
  • if you want to jump 10
  • Clear the rest of the line 0
  • Return to the beginning of the statement (gg) Start recording to register q (qq)
  • Yank words (yw) Go to the beginning of the next line (+) Paste to the left of the cursor (P)
  • Add (<C-A>) to the cursor position number (pasted previous line number)
  • Back to line beginning (0)
  • End Recording (q)
  • Specify the number of iterations and run the macro in register q with @q


2022-09-30 21:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.