feisty meow concerns codebase 2.140
parse_csv_line.h
Go to the documentation of this file.
1#!/usr/bin/env bash
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.
6#
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.
11#
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.
15#
16# Author: Chris Koeritz
17############################################################################
18
19declare -a csv_split=()
20
21# you can override the chosen separator if your data has tildes in it...
22if [ -z "$UNIQUE_SEPARATOR" ]; then
23 UNIQUE_SEPARATOR='~'
24fi
25
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
29# properly.
30function parse_csv_line()
31{
32 local parm="$1"; shift
33#echo line before is: $parm
34 csv_split=()
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.
39 OLD_IFS="$IFS"
40 IFS="$UNIQUE_SEPARATOR"
41 local csv_temp=($to_split)
42 IFS="$OLD_IFS"
43 # loop through and strip out the quotes.
44 i=0
45 while [ $i -lt ${#csv_temp[*]} ]; do
46 csv_split[$i]="$(echo ${csv_temp[$i]} | sed -e 's/"//g')"
47 i=$((i+1))
48 done
49}
50
51############################################################################
declare a csv_split