2 ############################################################################
3 # This function parses a line from a CSV file (you pass the line as the
4 # argument) into elements in an array. The CSV elements must be enclosed
5 # in double-quotes and then separated by a comma.
7 # Commas are replaced by tildes as the separator character in an attempt to
8 # allow elements to contain commas. If elements also contain tildes, a new
9 # separation character can be substituted by setting the variable
10 # UNIQUE_SEPARATOR to the value of that new separator character.
12 # Right now double-quote characters are also removed from the final output,
13 # so if one of you elements contains double-quotes this function will remove
14 # those double-quotes from within your element.
16 # Author: Chris Koeritz
17 ############################################################################
21 # you can
override the chosen separator
if your data has tildes in it...
22 if [ -z
"$UNIQUE_SEPARATOR" ]; then
26 # parses a line of CSV text and turns it into an array called
"csv_split".
27 # one defect of
this approach is that
if there are occurrences of the separator
28 # character in the middle of the quoted strings, they will not be handled
30 function parse_csv_line()
32 local parm=
"$1"; shift
33 #echo line before is: $parm
35 # fix the line so we don
't mistake embedded commas as separators.
36 to_split="$(echo "$parm" | sed -e "s/\" *, *\"/\"$UNIQUE_SEPARATOR\"/g")"
37 #echo line afterwards is: $to_split
38 # swap the IFS so we can find the breaks.
40 IFS="$UNIQUE_SEPARATOR"
41 local csv_temp=($to_split)
43 # loop through and strip out the quotes.
45 while [ $i -lt ${#csv_temp[*]} ]; do
46 csv_split[$i]="$(echo ${csv_temp[$i]} | sed -e 's/
"//g')"
51 ############################################################################