Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert comma separated values into a list of values using shell script

Tags:

bash

shell

unix

cut

I have csv data like:

a,b,c,d,e,f,g,h

I want this data in a list, one letter in each line. Is it possible is shell script? I have tried to extract each letter using cut command as shown below:

less list.txt | cut -d"," -f?

The command is working but the problem here is the number of fields is unknown. I have to place this command in a loop and iterate on the list so that I can extract the values one-by-one a redirect them to another file.

like image 861
Prashanth Avatar asked Jun 26 '15 10:06

Prashanth


2 Answers

Use tr to change , into newlines:

tr , "\n" < list.txt

See https://en.wikipedia.org/wiki/Tr_(Unix)

like image 50
Joe Avatar answered Oct 01 '22 09:10

Joe


You could use the tr command to transform each "," into a newline.

cat list.txt | tr "," "\n"

From then you can output each line wherever you want using a while read loop

cat list.txt | tr "," "\n" | while read LINE
 do
  echo "$LINE" >> ~/wherever/you/want
done

Or ...

while read LINE
 do
  echo "$LINE" >> ~/wherever/you/want
done <<< "$(cat list.txt | tr "," "\n")"

Either works.

like image 21
Alek Avatar answered Oct 01 '22 08:10

Alek