Search code examples
listcsvvim

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?


Solution

  • 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