0

Good, why can't I pass the value of the variable numIterations to the next expression and instead if it works for me if I put the value by hand?

echo "numIterations $numIterations"
(tr ' ' '\n' | sort | uniq -c | awk '{print "winner " $2 " appeared "$1 " times. Frequency is "$1*100 / $numIterations" %"}') < "final_winners.txt" > "final_output_winners.txt"

This is the output below:

numIterations 1000
winner 10 appeared 110 times. Frequency is 100 %
winner 11 appeared 90 times. Frequency is 100 %
...

$1 is 110, $numIterations is 1000, so the result must be 11%, no 100%

If i substitute $numIterations with 1000, the result is ok.

I am running bash 3.2 in osx 10.14.1. Thank you.

aironman
  • 837
  • 5
  • 26
  • 55

1 Answers1

2

Your variable is in single quotes, therefore it isn't expanded. In the awk part replace $numIterations with '"$numIterations"'.

Better alternative: Use awk -v ni="$numIterations" to set an awk variable and use ni inside the awk script. Example for clarity:

$ x=7
$ echo awk 'BEGIN {print 1 * $x}'
awk BEGIN {print 1 * $x}              # this is literally what awk sees
$ awk 'BEGIN {print 1 * $x}'
0                                     # because $x is not set in awk
$ awk -v x="$x" 'BEGIN {print 1 * x}'
7
Socowi
  • 25,550
  • 3
  • 32
  • 54