Four Ways to Pass Shell Variables in AWK
Here I am trying to show you 4 different ways to pass shell variable value to AWK
- 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 - 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 - 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 - 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