PDA

View Full Version : awk question




Big Dave
Dec 2, 2010, 03:43 PM
I would like to read in a variable into a BASH script using awk. I am failing at the correct syntax. Could someone help?

variable=`awk '{ if ( $x >= .9 ) print " 254 0 0"
else if ( $x >= .8 ) print " 0 254 0"
else print " 0 0 254 "}'`



chown33
Dec 2, 2010, 06:53 PM
Do you want the $x to expand to the then-current value of the shell variable 'x'?

If so, you'll have to do something about the single-quotes, because single-quotes prevent all shell-variable expansion.

I can post an answer, but I need to know what you want from the $x.

Big Dave
Dec 2, 2010, 07:09 PM
Do you want the $x to expand to the then-current value of the shell variable 'x'?

If so, you'll have to do something about the single-quotes, because single-quotes prevent all shell-variable expansion.

I can post an answer, but I need to know what you want from the $x.

chown33,
You nailed me last time on an expansion error. I will really be ashamed if I have made the same mistake. To give you a little more information, $x will be a value from 0 to 1. It can have as many as 8 places following the decimal. I script mainly in BASH and I know that decimals are bad in BASH. I was hoping that awk could handle the job. I basically want to make some conditions to where $x falls between 0 and 1. I want to then assign a three variable array based on the comparison.

chown33
Dec 2, 2010, 07:24 PM
Here's the answer (well, one possible answer):

variable=`awk </dev/null -v xyzzy="$x" 'END { if ( xyzzy >= .9 ) print " 254 0 0"
else if ( xyzzy >= .8 ) print " 0 254 0"
else print " 0 0 254 "}'`


There were multiple problems:

1. Single-quotes were preventing the expansion of $x in the quoted program. Oops.
2. You didn't give awk any input, so it's reading stdin. Not good.
3. If you gave it an empty input stream, then no pattern-match will occur, so no output. Not good.

To solve these:

1. I avoided adding escaped double-quotes by using an awk variable (xyzzy),
which is assigned a value by the -v option.
2. I gave it /dev/null to read from, which will give an immediate EOF.
3. I used the special pattern END, which is executed when EOF occurs on input.

Big Dave
Dec 2, 2010, 07:30 PM
Obviously I need to properly learn how to use expansion. I admit I am a novice. I really appreciate your help. Thanks again!

chown33
Dec 2, 2010, 07:55 PM
You're welcome.

At least you ask interesting questions that don't look like homework or LMGTFYable. And you post code first time.