Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding/generating content automatically in Vim

I have a huge list of numbers and I would like to add content on the end of each line. It's something like this:

Before:

123123
123123
13234
124125
12634
5234

After:

123123, 1
123123, 2
13234, 3
124125, 4
12634, 5
5234, 6

A couple of points:

  1. I know that :range s/oldpattern/newpattern/ will substitute the oldpattern by the new one.

  2. I know that for i in range(begin, end) | something | endfor can generate those extra numbers.

However, I don't know if it's possible to combine them to do what I want (or if there's a different way to do it). Does anybody knows how can I add those extra values automatically? I'm quite sure that it's possible using Vim, but I don't know how.

like image 937
Jeanderson Candido Avatar asked Nov 17 '12 21:11

Jeanderson Candido


2 Answers

You can do this by visually selecting the area then typing

:s/$/\=', '.(line('.')-line("'<")+1)<CR>

(range is added automatically when you type : from visual mode). Visual mode is needed to get line("'<") thing, if you are fine with typing line number in place of it use any range.

like image 117
ZyX Avatar answered Nov 11 '22 14:11

ZyX


I'd do

:%!nl
:%s/\v^\s*(\d+)\s+(.*)$/\2, \1/g

nl will (by default) skip numbering empty lines

Or as a oneliner

:exec "%!nl"|%s/\v^\s*(\d+)\s+(.*)$/\2, \1/g
like image 2
sehe Avatar answered Nov 11 '22 16:11

sehe