The following function uses awk to convert a csv line to multiple lines. I then can assign the output to an array to be able to access the fields.
function csv_to_lines() {
echo $@ | awk '
BEGIN {FPAT = "([^,]*)|(\"[^\"]+\")";}
{for(i=1; i<=NF; i++) {printf("%s\n", $i)}}'
}
line='A,B,"C,D",E'
arr=($(csv_to_lines $line))
printf '%s,' "${arr[@]}"
However, this doesn't work for empty fields. For example:
line='A,,,,,"C,D",E'
arr=($(csv_to_lines $line))
printf '%s,' "${arr[@]}"
Outputs
A,"C,D",E,
But I expected
A,,,,,"C,D",E,
Evidently, all empty lines are ignored when assigning to the array. How do I create an array that keeps the empty lines?
printf("%s\n", $i)=print $i. You also have a few shell errors in your script that copy/pasting it into shellcheck.net would tell you about.