OS/리눅스 & 유닉스

Four Ways to Pass Shell Variables in AWK

적외선 2012. 3. 20. 13:32

Four Ways to Pass Shell Variables in AWK

As we all know, not everyone is equal. This applies to AWK too. AWK in Solaris is a very old implementation compared the GNU AWK.

Here I am trying to show you 4 different ways to pass shell variable value to AWK

  1. This trick works on all flavours of AWK because it is taking advantage of shell substitution. Remember not to leave any space when you include a single quote, dollar variable, and a single quote in the AWK command
    $ one=111
    
    $ two=222
    
    $ awk 'BEGIN{a='$one';b='$two'}END{print a,b}' /dev/null
    111 222
    
  2. This works for all flavours of AWK too. AWK allows you to set their variable from the shell
    $ one=111
    
    $ two=222
    
    $ awk 'END{print a,b}' a=$one b=$two /dev/null
    111 222
    
  3. This will not work for Solaris awk. You have to use nawk. The -v flag allows you to assign AWK variable.
    $ one=111
    
    $ two=222
    
    $ nawk -v a=$one -v b=$two 'END{print a,b}' /dev/null
    111 222
    
  4. If your awk allows you to access the shell environment variables, you can use this trick. FYI, this will not work for Solaris awk.
    $ one=111
    
    $ two=222
    
    $ a=$one b=$two awk 'END{print ENVIRON["a"],ENVIRON["b"]}' /dev/null
    111 222