It might take a fool to write a CSV parser in zsh.
Here's one.
It should work in bash too.
Here's one.
It should work in bash too.
#
# read a csv formatted file
# filed1,field2,etc
# fields can be quoted if they contain a comma
#readcsv()
{
ifs=$IFS
IFS=$'\n'
csvfile=$CSV
# read full file stripping EOLs
table=( $(cat $csvfile | tr -d "\r") )
# line scan
for line in $table
do
campi=( )
campo=''
ncampo=1
quoted=0
# we scan all the line
for (( i=1 ; i <= $#line ; i++ ))
do
carattere=''
if [ $line[$i] = \" ]
then
# we found some quotes to strip out
if [ $quoted = 1 ]
then
# closing quotes
quoted=0
else
# opening quotes
quoted=1
fi
else
if [ $line[$i] = , ]
then
# comma found
if [ $quoted = 0 ]
then
# if it's out of quotes then it's the end of a field
campi[ncampo]=$campo
let ncampo=$ncampo+1
campo=''
else
carattere=','
fi
else
carattere=$line[$i]
fi
fi
# append char to current field
campo=$campo$carattere
done
# at the end of the line all goes into the last field
campi[ncampo]=$campo
# now you can access all the field with an array
#$campi[1]
#$campi[2]
#$campi[n]
done
IFS=$ifs
IFS=$ifs
}
No comments:
Post a Comment