Using variable within awk

Hi All,

I have a tab-delimited input file in which the 7th column contains the date in the format given below

Aug 29 2013 12:00AM

I have assigned this date value to a variable like

d1="Aug 29 2013 12:00AM"

I want to compare the 7th column in the file with this variable d1 and if it matches, I want the whole line to be copied to a separate file.

I am doing the below but not getting the desired result

cat input_file | awk -F"\t" '{if ($7=="$d1") print $0}'

Can you help?

Thanks

Hi,
You can try:

cat input_file | awk -F"\t" '{if ($7=="'$d1'") print $0}'

Regards.

it's giving the below error:

 syntax error The source line is 1.
 The error context is
                {if >>>  ($7=="Aug <<<
 awk: The statement cannot be correctly parsed.
 The source line is 1.
        awk: There is a missing } character.
        awk: There is a missing ) character.

Use -v for using variable in awk. and avoid use of cat if you are using awk.

d1="Aug 29 2013 12:00AM"

 awk -F"\t" -v D1="$d1" '{if ($7==D1) print $0}' input_file

Yep,
I forget to protect variable:

cat input_file | awk -F"\t" '{if ($7=="'"$d1"'") print $0}'

First double quote for awk
simple quote to come back shell for interpreting variable d1
second double quote for protect space in variable value

Regards.

You should not add variable to awk this way, do like pamu shows, or like this.
awk -F"\t" '{if ($7==D1) print $0}' D1="$d1" input_file

If yo do not have space, only tab, you can remove the field separator too.
awk '{if ($7==D1) print $0}' D1="$d1" input_file

You get several Useless Use of Cat Awards

There are two reliable ways to get a variable into awk, that is neither of them.

# method 1
awk -v VAR=value '{ ... }'

# method 2
awk '{ ... }' VAR=value

Your method is prone to syntax errors, should your variable accidentally contain any quotes or awk code.

As a side note:

  1. Some old awk implementations don't support the -v var... syntax:
bash-3.00$ awk -v x=1 '{ print x }' <<< a
awk: syntax error near line 1
awk: bailing out near line 1
bash-3.00$ awk '{ print x }' x=1  <<< a
1
bash-3.00$ type awk; uname -sr
awk is hashed (/usr/bin/awk)
SunOS 5.10

You should use either nawk or the X/Open version of awk (/usr/xpg4/bin/awk) on Solaris anyway.

  1. When you're using the syntax below, the value(s) is/are not available in the BEGIN block:
bash-3.00$ awk 'BEGIN { print x }' x=1 <<< a

bash-3.00$ /usr/xpg4/bin/awk 'BEGIN { print x }' x=1

bash-3.00$ nawk 'BEGIN { print x }' x=1

bash-3.00$

@Corona688: I do not disagree, I only correct the error of the single quote on the syntax of the example.
But, it is true that I have also fixed the method.:o

Regards.