6

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
martin
  • 3,149
  • 1
  • 24
  • 35
user3492304
  • 153
  • 2
  • 4
  • 11
  • How do you want to handle multiple lines? Would the first field of the second line be placed in `arr[3]`? Or does the array only need to hold one line at a time, being reset on each iteration? – chepner Aug 12 '14 at 11:57
  • You may want to take a look at the following [answer](http://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash). – wearp Aug 12 '14 at 12:54

1 Answers1

14

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
konsolebox
  • 72,135
  • 12
  • 99
  • 105