SWHJ
SWHJ

Reputation: 494

How to convert a list to CSV with Vim?

I want this list:

one
two
three
four
five
six

to come out as:

one,two,three,four,five,six

if I use Vim's search and replace like:

:%s/\n/,/g

it will come out like:

one,two,three,four,five,six,

Is there a way to avoid the last comma?

Upvotes: 0

Views: 346

Answers (2)

mattb
mattb

Reputation: 3063

You could append a comma to all but the last line before running the substitution command (see :help :normal):

:1,$-1 norm A,

Then of course don't add a comma during the substitution:

:%s/\n

Upvotes: 3

romainl
romainl

Reputation: 196751

If you really want to do it with a single substitution:

:%s/\n\(.\)/,\1

\n matches every newline, including the one on the last line, so we leave the last newline out by adding the character immediately after the newline. That character is put in a capture group to allow us to reuse it in the replacement part.

Frankly, the following does the job with the same amount of keystrokes but with a lot less head scratching:

:%s/\n/,|norm $x

Upvotes: 3

Related Questions