Sample Header Ad - 728x90

How can I use a variable in awk command

1 vote
1 answer
2662 views
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.
Asked by anonymous (11 rep)
Aug 28, 2020, 09:26 AM
Last activity: Jun 25, 2025, 10:52 AM