Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

For example, imagine I had the following text:

/ apple
/ orange
/ banana
/ bread

How could I efficiently add consecutive integers in a column to make?

/1 apple
/2 orange
/3 banana
/4 bread

Note that in real problems, the list might be 20, 50, or more lines long.

share|improve this question

2 Answers 2

One idea is to use vim's macro feature. Position the cursor on the first / in / apple, and do:

a1<Esc>

to insert the first number to start everything off (<Esc> being the escape key). Then with your cursor on the newly inserted 1, record the macro (into slot q):

qqyiwj0p<C-a>q

Now you should have the first 2 lines numbered. You now can run the macro n-2 times, where n is the total number of lines you have. As an example, if you had 50 lines, we run the macro 48 times since we already filled in 2 lines manually:

48@q
share|improve this answer

You could use the "pipe through an external command" feature that vim has. Open the file in vim, then do this:

:%!cat -n | awk '{print $2, $1, $3;}' | sed 's/ //'

You could probably dispense with the sed (which just deletes the first space in each line) by clever awk code. I just couldn't get it to work in 30 seconds, so I slopped out with sed.

share|improve this answer
    
Personally, I'd be inclined to just pipe it through cat -n and do the rest with visual block mode. –  Random832 Oct 13 '11 at 17:12
1  
Or pipe through nl, which allows the number format to be fine-tuned. –  Gilles Oct 13 '11 at 23:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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