Sahil
Sahil

Reputation: 9486

How to insert Command Line argument of shell script in AWK?

I have to find all of the record which have a particular data which I am gonna pass as the command line argument.

awk expression is like this(Date is in this format :'02/08/2013')

cat records.txt| awk -F ',' '$4 ~ /02/08/2013/ {print $1 $2}'

Here 4th column is the date column.

What I want to do is that, provide the date as the first argument and compare it.

I tried this,But it is not working.

cat records.txt| awk -F ',' -v awkvar="$1" '$4 ~ /^"awkvar/ {print $1 $2}'

Here the date column starts with " quote, so I am telling to look for the records who start with "+awkvar the given date.

Can anyone help me with this?

Edit:

awk -F ',' -v var1="$1" '$4 ~ /^"2013/ {print $1 $2}' {This one is working, as I am directly comparing the record with 2013}

when I do this

awk -F ',' -v var1="$1" '$4 ~ /^"var1/ {print $1 $2}' , it does not return anything, what is the difference.

Upvotes: 2

Views: 2892

Answers (1)

Gilles Quénot
Gilles Quénot

Reputation: 185660

To pass variables to awk, use

awk -v awkvar=$value '{print awkvar}'

That said, no need to pipe cat | awk (useless use of cat) so finally :

awk -F, -v awkvar="$1" '$4 ~ "^\""awkvar {print $1 $2}' records.txt

Upvotes: 4

Related Questions