Can we use shell variables in awk?

Yes, you can use the shell variables inside awk. There are a bunch of ways of doing it, but my favorite is to define a variable with the -v flag:

$ echo | awk -v my_var=4 '{print "My var is " my_var}'
My var is 4

Just pass the environment variable as a parameter to the -v flag. For example, if you have this variable:

$ VAR=3
$ echo $VAR
3

Use it this way:

$ echo | awk -v env_var="$VAR" '{print "The value of VAR is " env_var}'
The value of VAR is 3

Of course, you can give the same name, but the $ will not be necessary:

$ echo | awk -v VAR="$VAR" '{print "The value of VAR is " VAR}'
The value of VAR is 3

A note about the $ in awk: unlike bash, Perl, PHP etc., it is not part of the variable’s name but instead an operator.

Leave a Comment