Skip to main content
edited tags
Link
αғsнιη
  • 41.9k
  • 17
  • 75
  • 118
Source Link

Print each field of CSV on newline without knowing number of fields

I was playing with IFS today and created a quick text file with a list of numbers separated by commas on 1 line.

1,2,3,4,5 

I then tried to write a script to print each number on a newline. I was able to make it work, but I had to know how many fields there were. I'm trying to figure out how to do this on a list that's much longer where I wouldn't want to specify every field.

#!/bin/bash IFS=, while read num1 num2 num3 num4 num5 do printf $num1"\n" printf $num2"\n" printf $num3"\n" printf $num4"\n" printf $num5"\n" printf "\n" done < "$1" 

This gives me the output:

keismbp13b:tmp$ ./ifs.sh list 1 2 3 4 5 keismbp13b:tmp$ 

I'm thinking I may have to use awk or something similar to separate the list onto newlines but I am curious if there is another way.

Thanks!

I also realized just after posting that I could do this

tr , "\n" < list 

Is there anyway to do this without separating the list first?