awk question

Discussion in 'Mac Programming' started by Big Dave, Dec 2, 2010.

  1. macrumors 6502

    Joined:
    Nov 27, 2007
    Location:
    Crestview, Fl
    #1
    I would like to read in a variable into a BASH script using awk. I am failing at the correct syntax. Could someone help?
    Code:
    variable=`awk '{ if ( $x >= .9 ) print " 254 0 0"
                         else if ( $x >= .8 ) print " 0 254 0"
                         else print " 0 0 254 "}'`
    
     
  2. macrumors 603

    Joined:
    Aug 9, 2009
    #2
    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.
     
  3. Big Dave, Dec 2, 2010
    Last edited: Dec 2, 2010

    thread starter macrumors 6502

    Joined:
    Nov 27, 2007
    Location:
    Crestview, Fl
    #3
    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.
     
  4. macrumors 603

    Joined:
    Aug 9, 2009
    #4
    Here's the answer (well, one possible answer):

    Code:
    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.
     
  5. thread starter macrumors 6502

    Joined:
    Nov 27, 2007
    Location:
    Crestview, Fl
    #5
    Obviously I need to properly learn how to use expansion. I admit I am a novice. I really appreciate your help. Thanks again!
     
  6. macrumors 603

    Joined:
    Aug 9, 2009
    #6
    You're welcome.

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

Share This Page