Calculation error with awk
I have a script:
#!/bin/bash var1=1111688 var2=374335 prctg=`echo | awk '{print 100 - $var2\*100/$var1}'` echo "$prctg" prctg1=$((echo | awk '{print 100 - $var2\*100/$var1}')) echo "$prctg1" But when I invoke it, it's giving me following error: awk: syntax error near line 1 awk: illegal statement near line 1 testscript.sh: syntax error at line 6: `prctg1=$' unexpected Could anybody rectify, where I am making mistake? Running it on Solaris 10. |
Code:
prctg=`echo | awk '{print 100 - $var2\*100/$var1}'`
Code:
prctg=`awk -vvar1="$var1" -vvar2="$var2" 'BEGIN{print 100 - var2*100/var1}'` Code:
prctg1=$((echo | awk '{print 100 - $var2\*100/$var1}')) Code:
# use $() instead of `` Quote:
|
Ntubski, thanks for your reply. But unfortunately none of your suggested commands worked! I am running it in Solaris 10 and I am running this script with #!/bin/bash. Bash version installed in my system is 3.00.16(1). If I am using following expression in my script:
prctg=`awk "BEGIN{print 100 - $var2*100/$var1}"` It gives the error: awk: divided by zero Else, all other commands give the error I already mentioned. Even if I change the shell to #!/bin/csh or #!/bin/tcsh, and set variables using "set <var-name>=<value>", it's still giving that same error as mentioned previously!! :( |
Can we see the whole code as it stands? If I run
Code:
$ var1=1111688 |
Quote:
#!/bin/bash var1=1111688 var2=374335 echo | awk "BEGIN{print 100 - $var2*100/$var1}" Output: 66.3273 Thanks everyone for your responses!! |
Quote:
|
Please use ***[code][/code]*** tags around your code and data, to preserve the original formatting and to improve readability. Do not use quote tags, bolding, colors, "start/end" lines, or other creative techniques.
awk operates on values fed to it through stdin or files. It doesn't do stand-alone operations except inside the BEGIN part of the statement. Code:
echo "$var1 $var2" | awk '{ print 100 - $2 * 100 / $1 }' Code:
echo "100 - $var2 * 100 / $var1" | bc By the way, Be careful about precedence order in mathematical expressions. These two commands will give different values: Code:
And finally, $(..) is highly recommended over `..`. |
All times are GMT -5. The time now is 01:43 PM. |