How to split a list by comma not space How to split a list by comma not space shell shell

How to split a list by comma not space


Using a subshell substitution to parse the words undoes all the work you are doing to put spaces together.

Try instead:

cat CSV_file | sed -n 1'p' | tr ',' '\n' | while read word; do    echo $worddone

That also increases parallelism. Using a subshell as in your question forces the entire subshell process to finish before you can start iterating over the answers. Piping to a subshell (as in my answer) lets them work in parallel. This matters only if you have many lines in the file, of course.


Set IFS to ,:

sorin@sorin:~$ IFS=',' ;for i in `echo "Hello,World,Questions,Answers,bash shell,script"`; do echo $i; doneHelloWorldQuestionsAnswersbash shellscriptsorin@sorin:~$ 


I think the canonical method is:

while IFS=, read field1 field2 field3 field4 field5 field6; do   do stuffdone < CSV.file

If you don't know or don't care about how many fields there are:

IFS=,while read line; do  # split into an array  field=( $line )  for word in "${field[@]}"; do echo "$word"; done  # or use the positional parameters  set -- $line  for word in "$@"; do echo "$word"; donedone < CSV.file