Help with awk if/else-statement

Hi all

I'm trying to write an awk script to process some text file based on the number of fields in each line. That is, if a line contains, for instance, 10 words, I'd like to process it differently than if it has 11 words. However, I don't seem able to get the if/else-statements correct.

This is the script:

#!/bin/awk
{
if ( NF = 10 )
print "10," NF "," $0
else
print "xx," NF "," $0
}

I'd expect that the script will output something like this:

10,10,line with 10 words
xx,13,line with 13 words

Instead I'm getting:

10,10,line with 10 words
10,10,line with 13 words

I changed the script to

{
if ( NF = 500 ) # of course, there are no lines with 500 fields!
print "500," NF "," $0
else
print "xx," NF "," $0
}

and now I'm getting this:

500,500,line with 10 words
500,500,line with 13 words.

It seems that instead of comparing "NF" to the number 10 (or 500), the script is SETTING the variable NF to 10 (or 500).
Why????



TIA, Tina

G5 Dual 1.8 (and lots of others, @ work and @ home), Mac OS X (10.5.6), iPhone 3G

Posted on Oct 23, 2009 3:22 AM

Reply
7 replies

Oct 23, 2009 7:20 AM in response to Tina Siegenthaler

The awk basic form is

selection { action }
selection { action }
....
selection { action }

where each line of the file is checked against each "selection" statement.

So you could have formed your awk as

#!/bin/awk
NF == 10 { print "10," NF "," $0; next }
NF == 11 { print "xx," NF "," $0; next }
{ print "everything else" }

Your way is NOT wrong, I'm just trying to point out alternate ways of using awk.

The same line may be processed by multiple "selection" statements which is why I included "next" in the { action } section.

You might find the following web page interesting awk reading.
<http://h30097.www3.hp.com/docs/base doc/DOCUMENTATION/V51BHTML/ARH9WBTE/WKXXXXXX.HTM>

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Help with awk if/else-statement

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.