1

I'm trying to get a grip on awk.

Suppose I have an input:

this header
fred blah 1 blank
fred blah 1 blank
huh blah 2 blank
fred blah 3 blank
fred blah 3 blank

and after I use the following awk script,

#!/usr/bin/awk -f
{
    if ( NF <=2 ) {
            print $0
    };
    if ( NF>=3 && $3=1)
     {
            print $0
    }
}

I expect to get this output:

this header
fred blah 1 blank
fred blah 1 blank

But instead I get this output:

this header
fred blah 1 blank
fred blah 1 blank
huh blah 1 blank
fred blah 1 blank
fred blah 1 blank

where $3 has been turned into the condition.

Why does this happen?

And how do I tweak my awk script to give me the output that I expect?

2

do not mistake

a = b

and

a == b

even with if ( ) test, a = b is setting b's value to a. (even if a is $3).

you should write :

$3 == 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.