Linux vi tricks for converting vertical lists to horizontal comma separated lists

:: Linux vi tricks for converting vertical lists to horizontal comma separated lists ::

I have recently found that I need to do this almost every day. Here’s my little note on how I can do this quickly in vi.

First take your list of files vertically sorted and open them in vi.

#> vi myfile.txt
Bob
Joe
Jim
Seth
Sam
Sarah
Bill
Amy
Anne
Beth

—-
Next, tack on a comma to the end of each line with this vi command:

%s/$/,/g

Which gives you this:

Bob,
Joe,
Jim,
Seth,
Sam,
Sarah,
Bill,
Amy,
Anne,
Beth,
—-
Once you have all your lines ending in a comma, remove all the line breaks from the end of each line with this vi command:

%s/\n//

Which gives you this:

Bob,Joe,Jim,Seth,Sam,Sarah,Bill,Amy,Anne,Beth,

—-
Done.

I have been using this mostly for converting lists of IP addresses to comma separated for use in Linux Fabric scripts.

Enjoy!
K-Dog

:wq

Comments

  1. alcoholfueledmachine says:

    Pretty legit!!!

  2. falseflag says:

    Instead of doing multiple search and replaces, couldn’t you just do:

    :%s/[\r\n]/,/g