allowing links to see if there are really any remaining problems
[feisty_meow.git] / scripts / text / parse_csv_line.h
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.
5 #
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.
10 #
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.
14 #
15 # Author: Chris Koeritz
16 ############################################################################
17
18 declare -a csv_split=()
19
20 # you can override the chosen separator if your data has tildes in it...
21 if [ -z "$UNIQUE_SEPARATOR" ]; then
22   UNIQUE_SEPARATOR='~'
23 fi
24
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
28 # properly.
29 function parse_csv_line()
30 {
31   local parm="$1"; shift
32 #echo line before is: $parm
33   csv_split=()
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.
38   OLD_IFS="$IFS"
39   IFS="$UNIQUE_SEPARATOR"
40   local csv_temp=($to_split)
41   IFS="$OLD_IFS"
42   # loop through and strip out the quotes.
43   i=0
44   while [ $i -lt ${#csv_temp[*]} ]; do
45     csv_split[$i]="$(echo ${csv_temp[$i]} | sed -e 's/"//g')"
46     i=$((i+1))
47   done
48 }
49
50 ############################################################################