One liner to turn a column of text into a comma separated list

Spread the love

You have the following list:

Firstline
Secondline
Thirdline
Fourthline
Fifthline
Sixthline

You want to turn it into something that looks like this:

Firstline,Secondline,Thirdline,Fourthline,Fifthline,Sixthline

All you have is a stick of bubble gum, a broken lightbulb, and a bash shell with the usual tools installed. How would you do it?

Here are a few suggestions.

perl -pi.bak -e 'unless(eof){s/\n/,/g}' textfile

This will produce a backup called textfile.bak and modify the original file.

A rather involved sed one liner could do it:

sed -n 's/.*/&,/;H;$x;$s/,\n/,/g;$s/\n\(.*\)/\1/;$s/\(.*\),/\1/;$p'

Using tr:

cat textfile | tr '\n' ','

There are numerous other possibilities. Free to make suggestions. Also, how would you reverse the process?

Have you read the breakthrough novel of the year? When you are done with that, try:

In Search of Sungudogo by Greg Laden, now in Kindle or Paperback
*Please note:
Links to books and other items on this page and elsewhere on Greg Ladens' blog may send you to Amazon, where I am a registered affiliate. As an Amazon Associate I earn from qualifying purchases, which helps to fund this site.

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *