Saturday, 21 November 2015

How to Use Shell Variable in AWK

The -v option of AWK can be used to pass shell variables to awk command.

If we use V_user directly inside AWK, it will not work and we will not get what we want

$ V_User="Champ"
$ awk 'BEGIN{print "Hello=>" $V_User}'

Output:Hello=>

$ V_User="Champ"
$ awk -v x=${V_User} 'BEGIN{print "Hello=>" x}'

Output: Hello=>Champ

If we want to use multiple shell variables inside AWK below code will do it

$ V_User="Champ"
$ V_Msg="Welcome"

$ awk -v x=$V_Msg -v y=$V_User 'BEGIN{ print x, y}'

Output: Welcome Champ

$ V_Msg="Hello"
$ V_User="Champ"
$ awk 'BEGIN{x='$V_Msg';y='$V_User'} END{print x,y}' /dev/null
$ echo "" | awk 'BEGIN{x='$V_Msg';y='$V_User'} END{print x,y}'

Output: Hello Champ

awk 'END{print x,y}' x=$V_Msg y=$V_User /dev/null
$ echo ""awk 'END{print x,y}' x=$V_Msg y=$V_User

Output: Hello Champ

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...