Four Ways to Pass Shell Variables in AWK

OS/리눅스 & 유닉스 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

'OS > 리눅스 & 유닉스' 카테고리의 다른 글

awk 변수 shell 변수에 저장  (0) 2012.03.20
awk  (0) 2012.03.20
shell file read line  (0) 2012.03.20
awk 외부 변수 참조  (0) 2012.03.20
쉘 (shell) 프로그래밍  (0) 2012.03.20
: