Hrishikesh Barman Hrishikesh Barman - 2 years ago 68
Linux Question

How to match to a shell variable in awk?

I am trying to match a shell variable with the second column separated by commas.
So I've set $INOW to ls and the command looks like this

awk -F"," '$2 == $INOW {print "yeah it's there"}' commands.csv

I have tried putting quotes around $INOW. no difference. How do i make a match to the shell variable?

Answer Source

You cant use shell variables directly in awk. Rather you can create an awk variable using -v


$ a_variable=hello
$ awk -v var="$a_variable" "{print var}"

So in your case you can write like,

$ awk -F"," -v inow="$INOW" '$2 == inow {print "yeah its there"}' commands.csv
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download