Pages

Friday, May 18, 2018

Turn a list into a CSV file

Hello today I'm showing you two simple ways to turn a list into a comma separated (CSV) output. This is helpful if you need to import the output into a spreadsheet. 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

BASH Script
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,

SED Script
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.

No comments:

Post a Comment