When I try to read a file and parse CSV into an array using IFS, the array is missing the last element if the last element has no value. I want to sanitize by using the value of ${#array[@]}
to ensure the CSV has the correct number of columns but for rows with a null last column the behavior is incorrect.
What am I missing?
test.sh:
#!/bin/bash
while read line; do
oldifs=$IFS
IFS=','
array=($line)
IFS=$oldifs
echo "${array[@]} : num_elements =${#array[@]}"
done < $1
list.csv:
1,2,3,4,5,6,7,8,9
1,,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8,
Output:
$ ./test.sh list.csv
1 2 3 4 5 6 7 8 9 : num_elements =9
1 3 4 5 6 7 8 9 : num_elements =9
1 2 3 4 5 6 7 8 : num_elements =8