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

arraysbashshellsplit

I want to read a file line by line, split each line by comma (,) and store the result in an array. How to do this in a bash shell script?

Sample line in my comma separated file

123,2014-07-21 10:01:44,123|8119|769.00||456|S

This should be the output after splitting:

arr[0]=123 arr[1]=2014-07-21 10:01:44 arr[2]=123|8119|769.00||456|S

Best Solution

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 FD
if the -u option is supplied.  The line is split into fields as with word
splitting, and the first word is assigned to the first NAME, the second
word to the second NAME, and so on, with any leftover words assigned to
the last NAME.  Only the characters found in $IFS are recognized as word
delimiters.

  -a array  assign the words read to sequential indices of the array
            variable ARRAY, starting at zero