3

My shell script is giving the following error: Runtime error (func=(main), adr=5) : Divide by zero but I don't see where I could be dividing by zero? I have found other people with similar issues but there solutions are highly specific and can't replicate them within my script. Here is my script:

dir=$folder
cd folder

shop1=$1
mean1=4.78
n1=127

shop2=$2
mean2=4.75
n2=324

grep -P -o '(?=<Rating>).*' $hotel1 |
awk '{ sub(/<Overall>/, ""; print }' |
awk '{sum+=$1; sumsq+=$1*$1} END {print sqrt(sumsq/NR - (sum/NR)**2)}'

grep -P -o '(?=<Rating>).*' $hotel2 |
awk '{ sub(/<Overall>/, ""; print }' |
awk '{sum+=$1; sumsq+=$1*$1} END {print sqrt(sumsq/NR - (sum/NR)**2)}'

md=0.03
d1=0.003
d2=0.0038
d1d2=$(echo "d1 + d2" | bc)
sq=0.069
tstat=$(echo "md / sq" | bc)

My script basically will eventually calculate the t-statistic from my two data files, to do this it first calculates the standard deviation of each file. Thanks for your time.

John Smith
  • 679
  • 1
  • 9
  • 17

1 Answers1

5

It's not awk, here is the problem

tstat=$(echo "md / sq" | bc)

you have to refer to bash variables with $ prefix.

Needless to say, all of your script can be simplified into one awk

karakfa
  • 66,216
  • 7
  • 41
  • 56
  • Doesn't this also round the result to an integer? (Probably not good for a _t_-value.) – e0k Feb 25 '16 at 19:28
  • So tstat=$(echo "$md / $sq" | bc) ? If thats the case then wouldn't I need to change the d1d2 line aswell – John Smith Feb 25 '16 at 19:29
  • 1
    Just write the whole thing in awk and you don't have to worry about stuff like this. Sometimes simplicity wins. – e0k Feb 25 '16 at 19:31
  • 1
    @John Smith, for both, it's consistent. For summation it won't fail but won't give the result you want either. – karakfa Feb 25 '16 at 19:32
  • I know but I don't know how to :p – John Smith Feb 25 '16 at 19:32
  • I think I wrote a similar code here. http://stackoverflow.com/questions/35628103/how-do-i-calculate-the-standard-deviation-in-my-shell-script/35629989#35629989 Isn't it the same thing? – karakfa Feb 25 '16 at 19:35
  • Why would my output when I 'echo $tstat' be 0? I did the math and it should be 0.027789? – John Smith Feb 25 '16 at 19:41
  • To get floating point result use `bc -l`, otherwise it's rounded to int. – karakfa Feb 25 '16 at 19:47