The UNIX and Linux Forums

The UNIX and Linux Forums (http://www.unix.com/index.php)
-   Shell Programming and Scripting (http://www.unix.com/shell-programming-and-scripting/)
-   -   Meaning of NF{ a[$1]=a[$1]" "$2 ; next }? (http://www.unix.com/shell-programming-and-scripting/128518-meaning-nf-1-1-2-next.html)

npatwardhan 01-25-2010 05:11 PM

Meaning of NF{ a[$1]=a[$1]" "$2 ; next }?
 
Hi Guys,

I have the following statement from a bigger script. Can someone please explain what it does?

Code:


NF{ a[$1]=a[$1]" "$2 ; next }
END{for (i in a) {print i,a[i] } }

Thanks.

Scott 01-25-2010 06:25 PM

Hi.

It's part of an awk script.

NF{...} means if there are more than zero fields in the current record (i.e. not a blank line) perform the action between { and }

An awk script is made up of patterns (conditions, really) and actions

PATTERN { ACTION }

If PATTERN evaluates to true, then ACTION is performed.

[NF is an awk variable giving the number of fields in the current record. If it's non-zero, ACTION is performed.]

{ a[$1]=a[$1]" " $2; next } means append the value of field two ($2) to an array (a) indexed by the value of field one ($1).

The END section is performed after all input files are processed.

for(i in a) means assign to i, in turn, each element of a
and print the index value i, followed by the value referenced by that index (a[i]).

The two lines you posted say: add field two to an array called a, indexed by distinct values of field one.

HTH :)

npatwardhan 01-25-2010 07:34 PM

Thanks for the explanation. That helps a lot.


All times are GMT -4. The time now is 01:22 AM.

Linux and Unix Supported by: vBulletin
Search Engine Optimisation provided by DragonByte SEO v1.1.4 (Pro) - vBulletin Mods & Addons Copyright © 2014 DragonByte Technologies Ltd.
The UNIX and Linux Forums Content Copyright ©1993-2013. All Rights Reserved.
Forum Operations by The UNIX and Linux Forums