Hi Experts,
I have created a table with columns as empname,empid,phone,shiftname. Now I am having a .csv file format which contains the shift datas of the employees. I have to fetch this file and compare with the table I created to send an alert to the specified user.
Can you please post sample input and desired output; it will help us help you. Please use code tags when posting the sample code/output.
I have publish this solution in this forum previously, but here it's again generic template to start csv parsing. If you need also " " support/parsing then need litle more.
#!/bin/kh or /bin/bash ...
#csvparse
# some sample.csv
echo "$(<<EOF
name;age;girlfriend;random
aa;11;yes;$RANDOM
bb;22;yes;$RANDOM
cc;33;no;$RANDOM
dd;44;no;$RANDOM
ee;55;yes;$RANDOM
ff;44;
;44;no;$RANDOM
aa;55;no;xx;zz
EOF
)" > sample.csv
### csvparser
lastfld=0
flds[0]=""
val[0]=""
oifs="$IFS"
deli=";"
defdeli=";"
outdeli="$deli"
str=""
#####################################
initcolnames()
{
Xcnt=$1
Xdeli=$2
Xstr=""
Xfld=1
while ((Xfld <= Xcnt ))
do
Xstr="${Xstr}col${Xfld}$Xdeli"
((Xfld+=1))
done
echo "$Xstr"
}
#####################################
setvar()
{
str="$*"
IFS="$deli"
val=($str)
IFS="$oifs"
last=${#val[@]}
f=0
while ((f<=last && f<=lastfld))
do
var="${flds[$f]}"
value="${val[$f]}"
eval $var=\"$value\"
((f+=1))
done
}
#####################################
showvar()
{
f=0
outstr=""
Xoutdeli="$outdeli"
while ((f<=lastfld))
do
var="${flds[$f]}"
(( f == lastfld )) && Xoutdeli=""
eval value=\""\$$var"\"
outstr="$outstr$value$Xoutdeli"
((f+=1))
done
echo "$outstr"
}
#####################################
clrvar()
{
f=0
while ((f<=lastfld))
do
var="${flds[$f]}"
eval $var=\"\"
((f+=1))
done
}
#####################################
colnames()
{
nf=0
while [ $# -gt 0 ]
do
opt="$1"
case "$opt" in
-c) nf=$2 # no colnames, create
shift
;;
-d) defdeli=$2
shift
;;
*) str="$*" ; break ;;
esac
shift
done
(( nf > 0 )) && str=$(initcolnames $nf "$defdeli" )
IFS="$deli"
flds=($str)
IFS="$oifs"
lastfld=${#flds[@]}
((lastfld-=1))
}
#####################################
# MAIN
#####################################
deli=";" # set input delimeter , or use -d option in colnames
outdeli=" | "
lineno=0
while read line
do
((lineno+=1))
(( lineno == 1 )) && colnames "$line" && continue # headerline = variable names
clrvar
setvar "$line"
echo "________________________________"
showvar
# example using values
[ "$name" = "cc" ] && echo "$name, age:$age"
done < sample.csv