With my code I am trying to sum up the values with the specific name of a column in a csv file, depending on the input of the name. Here's my code:
#!/bin/bash
updatedata() {
index=0
while IFS="" read -r line
do
IFS=';' read -ra array <<< "$line"
for arrpos in "${array[@]}"
do
if [ "$arrpos" == *"$1"* ] || [ "$1" == "$arrpos" ]
then
break
else
let index=index+1
fi
done
break
done < data.csv
((index=$index+1))
if [ $pos -eq 0 ]
then
v0=$(awk -F";", -v index=$index '{x+=$index}END{print x}' ./data.csv )
elif [ $pos -eq 1 ]
then
v1=$(awk -F";" '{x+=$index}END{print x}' ./data.csv )
elif [ $pos -eq 2 ]
then
v2=$(awk -F";" '{x+=$index}END{print x}' ./data.csv )
elif [ $pos -eq 3 ]
then
v3=$(awk -F";" '{x+=$index}END{print x}' ./data.csv )
fi
}
In the middle of the code you can see in v0=, I was trying to experiment a little, but I just keep getting errors:
First I tried this:
v0=$(awk -F";" '{x+=$index}END{print x}' ./data.csv)
but it gave me this error:
'awk: line 1: syntax error at or near }'
so then I decided to try this(as you can see in the code)
v0=$(awk -F";", -v index=$index '{x+=$index}END{print x}' ./data.csv )
And I got this error: 'awk: run time error: cannot command line assign to index type clash or keyword FILENAME="" FNR=0 NR=0'
I don't know what to do. Can you guys help me.
index
is a built-inawk
function. You may want to use another name for this variable (and use$(varname)
inawk
). You also should not have a comma after-F ';'
. Not turning this into an answer as a real answer should probably also point to better ways of doing this operation (the shell loop is probably not needed).