Tag Archives: text manipulation

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

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?