Home > Back-end >  How to convert a list to CSV with Vim?
How to convert a list to CSV with Vim?

Time:09-14

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related