Sunday, March 29, 2009

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
    

Labels: ,

4 Comments:

Blogger Unknown said...

Thank you for such a helpful post!
sonja

9:32 PM  
Blogger Diego Benavente said...

Thanks for the tricks!!

Just a comment: In HPUX with Korn shell (ksh) I just got to work the first way to pass shell variables in awk.

In my case I wanted to print out some fields of a CSV file separating awk output columns with a tab so I defined a variable

FIELD_SEPARATOR='"\t"'

and then I used it inside awk:

cat $FILE_CSV | awk -F "," 'BEGIN {separator='$FIELD_SEPARATOR'} { printf $1 separator $2 }'

and it worked! :)

PS: you have to use single quotes to pass the variable to awk but still with the field separator including its double quotes.

6:22 PM  
Blogger chihungchan said...

If you just want to convert comma to tab separated, sed can do a better job.

sed 's/,/\t/g'

8:41 PM  
Blogger Diego Benavente said...

What about this fifth way of passing a Shell variable to AWK?

ls | awk -v test=$HOME '{print test": "$1 }'

You just have to "declare" it with AWK's -v option.

By the way, there's an AWK built-in variable exactly meant to replacing the output field separator: OFS, a space by default.
Usage:
BEGIN {OFS=":"}

1:05 AM  

Post a Comment

<< Home