Home > front end >  How to renumber lines using a vi command?
How to renumber lines using a vi command?

Time:11-02

I am trying to renumber the lines 2,$ in a file using vim a command, I know the command cat -n of nl, I can number the lines, but I didn't get the expected output:

I tried this :2,$s/^\([^,]\)// | 2,$!cat -n

input:

#,Name,Types,Total,HP,Attack,Weaknesses,Strength
493,Arceus,Normal,720,120,120,Fighting,strong
483,Dialga,Steel;Dragon,680,100,120,Fighting;Ground,strong
250,Ho-oh,Fire;Flying,680,106,130,Electric;Water;Rock,strong
.... moer 100 lines

expected output:

#,Name,Types,Total,HP,Attack,Weaknesses,Strength
1,Arceus,Normal,720,120,120,Fighting,strong
2,Dialga,Steel;Dragon,680,100,120,Fighting;Ground,strong
3,Ho-oh,Fire;Flying,680,106,130,Electric;Water;Rock,strong
....

CodePudding user response:

You can use \= to use a sub-replace-expression, and line('.') to get the current line number:

" The parenthesis around `line('.')-1` are not needed, but it seems clearer to me
:2,$s/^/\=(line('.')-1).','/

Edit: just realized you're actually replacing your first column, so you might actually want

:2,$s/^\d\ /\=line('.')-1/
  • Related