awk file redirection issue

So I'm writing a script which tries to parse human-readable addresses. Part of it is this:

print $2, implode(A,1,AN," "), CITY, PROV, POST, COUNTRY, CITYCOUNT>2;

CITYCOUNT is a variable between 0 and 3 counting the number of words in a city name. I'm trying to prnt 1 wherever that's greater than two, so I know which rows just might need manual intervention. The issue is that it doesn't compare CITYCOUNT and 2, it prints into a file named 2!

That awk promote an unquoted value into a string without being asked is pretty unusual, isn't it? What's going on?

1 Like

I can confirm the behaviour - precedence of the redirection operator - both on FreeBSD (awk version 20110810 (FreeBSD)) as well as on Ubuntu 17.10 (mawk 1.3.3 Nov 1996, Copyright (C) Michael D. Brennan).
What works well is enclosing the logical expression in parantheses.

1 Like

Thanks, that workaround works great. Just one of those weird syntax corners it seems.

Hello Corona688,

Apologies, if I got it wrong here(though I know you need with print trying to suggest it with printf ), I believe we could do this by printf like(examples here only):

 awk -v CITYCOUNT=0 'BEGIN{printf("%d\n",CITYCOUNT>2)}'
 0
 

OR

 awk -v CITYCOUNT=3 'BEGIN{printf("%d\n",CITYCOUNT>2)}'
 1
 

Thanks,
R. Singh

Using printf isn't a magic bullet here; as RudiC said in post #2, the way to get rid of the ambiguity between the logical expression CITYCOUNT > 2 and the output redirection > 2 is to use parentheses. Note that even with printf this can still be an issue. The following script:

awk '
BEGIN {
    for(CITYCOUNT = 1; CITYCOUNT <= 3; CITYCOUNT++) {
	printf "1 CITYCOUNT:%d CITYCOUNT>2:%d\n", CITYCOUNT, CITYCOUNT>2
	printf "2 CITYCOUNT:%d CITYCOUNT>2:%d\n", CITYCOUNT, (CITYCOUNT>2)
	printf("3 CITYCOUNT:%d CITYCOUNT>2:%d\n", CITYCOUNT, CITYCOUNT>2)
    }
}'

produces the following output on standard output (from the last two printf s in the loop:

2 CITYCOUNT: 1 CITYCOUNT > 2: 0
3 CITYCOUNT: 1 CITYCOUNT > 2: 0
2 CITYCOUNT: 2 CITYCOUNT > 2: 0
3 CITYCOUNT: 2 CITYCOUNT > 2: 0
2 CITYCOUNT: 3 CITYCOUNT > 2: 1
3 CITYCOUNT: 3 CITYCOUNT > 2: 1

(which both have a logical expression inside parentheses), and produces the following output from the first printf in the loop in a file named 2 :

1 CITYCOUNT: 1 CITYCOUNT > 2: 1
1 CITYCOUNT: 2 CITYCOUNT > 2: 2
1 CITYCOUNT: 3 CITYCOUNT > 2: 3

What also would work:

2 < CITYCOUNT
1 Like