Friday, May 18, 2018

Turn a list into a CSV file

Hello today I'm showing you two simple ways to turn a list that is in a column into a comma separated list that is on one line. You can do this one of two ways, with a BASH for loop or with SED.

We are going to use list.txt which is a small list of solar objects for this example. 

list.txt
earth
moon
mars
venus
saturn

BASHscript
for s in $(cat list.txt)
do echo -en "$s, "
done
-note - if you don't want spaces or commas use "$s" instead

man@earth> ./BASHscript
earth, moon, mars, venus, saturn,

SEDscript
cat list.txt |  sed ':a;N;$!ba;s/\n/, /g'

As you can see the SED statement is much shorter.

man@earth> ./SEDscript
earth, moon, mars, venus, saturn,

I hope someone out there finds this useful. If you have any questions or comments please post them below.