Hrishikesh Barman Hrishikesh Barman - 6 months ago 8
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

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

Example

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

So in your case you can write like,

$ awk -F"," -v inow="$INOW" '$2 == inow {print "yeah its there"}' commands.csv