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.

2 Answers 2

5

Use external unix command nl.

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

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.

1
  • Pretty nice solution too. I just now used it! Because it uses less code I accepted @buff’s answer. Commented Jul 17, 2014 at 8:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .