UNIX & Linux Forums

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

npatwardhan 01-25-2010 06: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?


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


Scott 01-25-2010 07:25 PM


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


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 08:34 PM

Thanks for the explanation. That helps a lot.

All times are GMT -4. The time now is 02:18 PM.

UNIX and Linux Forums
Search Engine Optimisation provided by DragonByte SEO v2.0.32 (Pro) - vBulletin Mods & Addons Copyright © 2017 DragonByte Technologies Ltd.
Unix & Linux Forums Content Copyright©1993-2017. All Rights Reserved.
Forum Operations by The UNIX and Linux Forums