Walker News

Uses Shell Variable In Awk Script

Question: Can awk use or access shell variable? If yes, how does the syntax look like?

With reference to GNU awk manual, there are two ways for this topic, but I choose to note down only the easier-to-remember syntax.

In this example, CNT is the exported shell variable. In order for awk to access the value of shell variable (in this case, CNT), I define a awk variable called ACNT and assign CNT value to it:
export CNT=2

echo "Value of shell variable CNT is " | awk -v ACNT=$CNT '{print $0 ACNT}'

Run that two commands at Linux command prompt, you’ll get this result:
Value of shell variable CNT is 2

It’s possible for awk to access more than one shell variable, e.g. the syntax becomes -v C1=$CNT1 -v C2=$CNT2 if to access two exported shell variables called CNT1 and CNT2 by awk variables C1 and C2 respectively:
export CNT1=7 CNT2=8

date -u -d "2013-01-01 00:00:00" +%s | \
 awk -v C1=$CNT1 -v C2=$CNT2 '{
   print "Epoch time: "$0" CNT1: "C1" CNT2: "C2}'

The output:
Epoch time: 1356998400 CNT1: 7 CNT2: 8

See, the syntax is easy to comprehend and remember. Isn’t it? Happy scripting :)

Custom Search

2014  •  Privacy Policy