first check-in of feisty meow codebase. many things broken still due to recent
[feisty_meow.git] / scripts / text / csv_to_array.sh
1 #!/bin/bash
2
3 ############################################################################
4
5 declare -a csv_split=()
6
7 # you can override the chosen separator if your data has tildes in it...
8 if [ -z "$UNIQUE_SEPARATOR" ]; then
9   UNIQUE_SEPARATOR='~'
10 fi
11
12 # parses a line of CSV text and turns it into an array called "csv_split".
13 # one defect of this approach is that if there are occurrences of the separator
14 # character in the middle of the quoted strings, they will not be handled
15 # properly.
16 function parse_csv_line()
17 {
18   local parm="$1"; shift
19 #echo line before is: $parm
20   csv_split=()
21   # fix the line so we don't mistake embedded commas as separators.
22   to_split="$(echo "$parm" | sed -e "s/\" *, *\"/\"$UNIQUE_SEPARATOR\"/g")"
23 #echo line afterwards is: $to_split
24   # swap the IFS so we can find the breaks.
25   oldIFS="$IFS"
26   IFS="$UNIQUE_SEPARATOR"
27   local csv_temp=($to_split)
28   IFS="$oldIFS"
29   # loop through and strip out the quotes.
30   i=0
31   while [ $i -lt ${#csv_temp[*]} ]; do
32     csv_split[$i]="$(echo ${csv_temp[$i]} | sed -e 's/"//g')"
33     i=$((i+1))
34   done
35 }
36
37 ############################################################################
38
39 # main script body:
40
41 for i in $*; do
42   echo reading $i
43   while read line; do
44 #    echo line is $line
45     csv_split=()
46     parse_csv_line "$line"
47
48     if [ ${#csv_split[*]} -lt 1 ]; then
49       echo did not see any fields in the split array.
50     else
51       echo line splits into ${#csv_split[*]} fields:
52       i=0
53       while [ $i -lt ${#csv_split[*]} ]; do
54         quoteless="${csv_split[$i]}"
55         echo "$i: $quoteless"
56         i=$((i+1))
57       done
58     fi
59   done < $i
60 done
61