How to read and split comma separated file in a bash shell script? How to read and split comma separated file in a bash shell script? shell shell

How to read and split comma separated file in a bash shell script?


Use read -a to split each line read into array based from IFS.

while IFS=, read -ra arr; do    ## Do something with ${arr0]}, ${arr[1]} and ${arr[2]}    ...done < file

If the third field can also contain commas, you can prevent it from being split by using finite non-array parameters:

while IFS=, read -r a b c; do    ## Do something with $a, $b and $c    ...done < file

From help read:

Reads a single line from the standard input, or from file descriptor FDif the -u option is supplied.  The line is split into fields as with wordsplitting, and the first word is assigned to the first NAME, the secondword to the second NAME, and so on, with any leftover words assigned tothe last NAME.  Only the characters found in $IFS are recognized as worddelimiters.  -a array  assign the words read to sequential indices of the array            variable ARRAY, starting at zero