page

May 31, 2019

How do I use shell variables in an awk script?

How do I use shell variables in an awk script?
https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script

- Using -v (The best way, most portable)

It uses the -v option: (P.S. use a space after -v or it will be less portable. E.g., awk -v var= not awk -vvar=)

variable="line one\nline two"
awk -v var="${variable}" 'BEGIN {print var}'
line one
line two
 
This should be compatible with most awk and variable is available in the BEGIN block as well:
If you have multiple variables:
awk -v a="${var1}" -v b="${var2}" 'BEGIN {print a,b}'

No comments:

Post a Comment