Weird awk problem

Hi,

I have a simple awk script:

BEGIN{}
{
$a=$2-$1;
print $a
}
END{if(NR==0){
print "0"
}
}

to which I provide the following input

2.9     14
22.2    27

When I invoke awk with

awk -f script input.txt

it returns me the following output

0
0

but if I change the awk script to

BEGIN{}
{
print $1
print $2
$a=$2-$1;
print $a
}
END{if(NR==0){
print "0"
}
}

I get the expected output, which is

14
2.9
11.1
27
22.2
4.8

I am not sure what the problem with the initial script is and why the two print statements in the beginning make any difference?

Is it something obvious that I am missing here?
Thanks.

The problem is the use of the variable name $a . Change this to a and all should be fine..

1 Like

Thanks! Confusion between bash variable and awk..the surprising thing is that the same script works okay in cygwin..

You're welcome. It is not entirely surprising.. If the variable a is not initialized then it is the empty string ( "" ).. So $a becomes $"" .

Some awks may interpret it in a numerical context and change it to 0 and so it turns into $0 (which is the record), which would give the proper answer, but it would work differently from what you might expect...

Other awks may not accept $"" and raise an error message

Yet other awks may assign it to $0 (because it is a numerical context), but reference $"" which may return 0, etc...

It is an ambiguous situation and it really depends on the specific awk implementation how this improper use of the variable gets handled..

1 Like

Hello jaime_123,

You can remove the use of variable here.

awk 'BEGIN{}
{
print $2 - $1;
}
END{if(NR==0){
print "0"
}
}'  Input_file

Thanks,
R. Singh

1 Like