1

Assume I have a text file containing some strings:

string_g
string_r
string_qqwer
string_p
string_f
string_3qw
string_e
string_qw

And I need to insert increasing or decreasing numbers before the strings:

001 string_g
002 string_r
003 string_qqwer
004 string_p
005 string_f
006 string_3qw
007 string_e
008 string_qw

Just to avoid confusion:

I do not want line numbers to be displayed. I know how that works. What I want is an actual number at the beginning of each string within the text.

Is there a way to do this automatically with vim?

I can mark the beginning of each string with CTRL-V then type : to enter the execute mode, which will allow me to execute command on the selection via :'<,'> but I’m stuck there.

4

Use external unix command nl.

:'<,'>!nl -w 3 -n rz -s' '
  • Can I start this from an arbitrary number such as say 180? – lord.garbage Jul 1 '14 at 10:52
  • 2
    Got it myself: :'<,'>!nl -v 180 -w 3 -n rz -s' ' (Sorry for asking and not first reading the manpage!) – lord.garbage Jul 1 '14 at 10:54
1

With vim only (don't use external command):

let i=1 | '<,'>g/^/ s//\=printf("%03d ",i) / | let i+=1

Change let i=1 to number you want to start.

  • Pretty nice solution too. I just now used it! Because it uses less code I accepted @buff’s answer. – lord.garbage Jul 17 '14 at 8:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.