olala
olala

Reputation: 4456

shell: write integer division result to a variable and print floating number

I'm trying to write a shell script and plan to calculate a simple division using two variables inside the script. I couldn't get it to work. It's some kind of syntax error.

Here is part of my code, named test.sh

    awk '{a+=$5} END {print a}' $variable1 > casenum
    awk '{a+=$5} END {print a}' $variable2 > controlnum
    score=$(echo "scale=4; $casenum/$controlnum" | bc)
    printf "%s\t%s\t%.4f\n", $variable3 $variable4 $score

It's just the $score that doesn't work.

I tried to use either

sh test.sh

or

bash test.sh

but neither worked. The error message is:

(standard_in) 1: syntax error

Does anyone know how to make it work? Thanks so much!

Upvotes: 0

Views: 255

Answers (3)

jkshah
jkshah

Reputation: 11713

If I understand your commands properly, you could combine calculation of score with a single awk statement as follows

score=$(awk 'NR==FNR {a+=$5; next} {b+=$5} END {printf "%.4f", a/b}' $variable1 $variable2)

This is with assumption that $variable1 and $variable2 are valid file names

Refer to @fedorqui's solution if you want to stick to your approach of 2 awk and 1 bc.

Upvotes: 1

ShinTakezou
ShinTakezou

Reputation: 9671

First your $variable1 and $variable2 must expand to a name of an existing file; but that's not a syntax error, it's just a fact that makes your code wrong, unless you mean really to cope with files containing numbers and accumulating the sum of the fifth field into a file. Since casenum and controlnum are not assigned (in fact you write the awk result to a file, not into a variable), your score computation expands to

score=$(echo "scale=4; /" | bc)

which is wrong (Syntax error comes from this).

Then, the same problem with $variable3 and $variable4. Are they holding a value? Have you assigned them with something like

  variable=...

? Otherwise they will expand as "". Fixing these (including assigning casenum and controlnum), will fix everything, since basically the only syntax error is when bc tries to interpret the command / without operands. (And the comma after the printf is not needed).

The way you assign the output of execution of a command to a variable is

  var=$(command)

or

  var=`command`

Upvotes: 1

fedorqui
fedorqui

Reputation: 289835

You are outputting to files, not to vars. For this, you need var=$(command). Hence, this should make it:

casenum=$(awk '{a+=$5} END {print a}' $variable1)
controlnum=$(awk '{a+=$5} END {print a}' $variable2)
score=$(echo "scale=4; $casenum/$controlnum" | bc)
printf "%s\t%s\t%.4f\n", $variable3 $variable4 $score

Note $variable1 and $variable2 should be file names. Otherwise, indicate it.

Upvotes: 2

Related Questions