arunmoezhi
arunmoezhi

Reputation: 3200

vi sequence number generation

I need to create a file in vi with this pattern. Is there a way to auto generate these lines using the first line

run 1 end
run 2 end
run 3 end
run 4 end
run 5 end
run 6 end

I can always do this in excel and then convert it to a text file and then switch to vi, but wanted to know if there a way to do it in vi so that I don't have to switch back to excel

Upvotes: 4

Views: 280

Answers (3)

mattn
mattn

Reputation: 7723

:put!=map(range(1,6),'\"run \".v:val.\" end\"')

Upvotes: 3

bcurcio
bcurcio

Reputation: 548

William's answer is very nice. I'll post another solution (it's a little more complicated), suppose you already have the first line

Y6P
:let g:I=1
:%g/\d/s/\d/\=g:I/|let g:I=g:I+1
  • let allows you to assign variables
  • g runs a global command
  • \d matches the number in the line
  • s is for substitute
  • \d is because you are going to write a number
  • \= is replace expression (see: :help sub-replace-\=)
  • g:I is the variable we are replacing in the expression and let increments the variable g:I

Upvotes: 2

William Pursell
William Pursell

Reputation: 212228

:help ctrl-a

^a increments the number under the cursor, which you can use in a macro. For your case, assuming you have the first line and the cursor is on it:

qaYpw^aq4@a

Should do the trick. This is the technique outlined in the help pages, modified with w to move the cursor forward to the number. Breaking it down:

  • qa start recording a macro in register a
  • Y yank the current line
  • p put the yank buffer below the current position and move to column 1 of the new row
  • w move forward one word (to the number)
  • ^a increment the number
  • q stop recording the macro
  • <count>@a apply the macro <count> times

    Another technique is to use an external tool. For example, if you already have the line and the cursor is on it:

    !!awk '1;{for(i=0;i<5;i++){$2+=1; print}}'
    

    Upvotes: 10

  • Related Questions