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 } }
 

Thanks.

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 :slight_smile:

Thanks for the explanation. That helps a lot.