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