5

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.

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Note that nl does not number blank lines, so it may be necessary to use nl -ba, depending on the desired behavior.
0
:%!awk '{print $0", "NR}'

or

:%!perl -lpe '$_.=", $."'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.