Search code examples
arrayslinuxbashawkcarriage-return

")syntax error: invalid arithmetic operator (error token is " when looping with array


I have a file like this:

<Overall>3
<Overall>1
<Overall>4
<Overall>5
...

Im trying to read the numbers after the overall tag, put them in an array and and after doing the operations with them to add the result to total.

    array=($(grep '<Overall>' "$file" | cut -d'>' -f 2))

    total=0
    for each in "${array[@]}"
    do
        total+=$(awk -v awkEach="${array[$each]}" 'BEGIN{print (awkEach-4.78)^2}')
    done

But I get: ")syntax error: invalid arithmetic operator (error token is "

I read all similar questions and tried different things, but nothing seems to work.


Solution

  • you can replace all with this,

    $ awk -F'>' '{sum+=($2-4.78)^2} END{print sum}' file
    
    18.1136