0

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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Sreten Jocić
  • 165
  • 1
  • 14
  • I do not know if it is your only problem, but you need to `declare -i total=0` if you want to use the `+=` operator outside an arithmetic expression such as `(())` and `$(( ))`. – Fred Feb 24 '17 at 19:32
  • The duplicate explains the reason for the error as posted, but it's not the only problem with the script. You can use the easier solution posted below, or to fix yours, use `total=$(awk -v total="$total" -v awkEach="$each" 'BEGIN{print total+(awkEach-4.78)^2}'` instead since 1. for loops in bash loop over values, not indices, and 2. bash can't add numbers with decimals. – that other guy Feb 24 '17 at 19:44

1 Answers1

4

you can replace all with this,

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

18.1136
karakfa
  • 66,216
  • 7
  • 41
  • 56