awk name pair values

Team,

I have a file like below

FILE:

NAM1,KEY1,VAL1
NAM1,KEY2,VAL2
NAM1,KEY3,VAL3
NAM2,KEY1,VALA
NAM2,KEY2,VALB
NAM2,KEY3,VALC

Output:

I have to build commands like below

<Script> VAL1 VAL2 VAL3 NAME1
<Script> VALA VALB VALC NAME2

Can you please help with awk command i can use inside a script to build and run the commands?

awk -F, '{a[$1]=($1 in a)? a[$1] OFS $3:$3} END {for (i in a) print "script" OFS a OFS i}' myFile
1 Like

Thank you so much.. Worked like a charm. however still cannot understand logic. If you get a chance can you please help explain

awk -F, '                            # use , as input field separator
{ # use array a index by $1 and value of indexed entry is built by
  # concatenating $3 to it separated by the value of OFS (space by default)
  #a[$1]=($1 in a)? a[$1] OFS $3:$3
  # the above can be rewritten as
  if ($1 in a)
     a[$1] = a[$1] OFS $3
  else
     a[$1]=$3
} 
END {
  # iterate through array a indexed by i - outputting a string script followed by
  # OFS (OutFieldSeparator - space by default), followed by value of array entry
  # iterated by i, followed by OFS and followed by the value of current iterator i.
  # iterator is the value of column $1
  for (i in a) 
    print "script" OFS a OFS i
}' myFile
awk -F, '{a[$1]=a[$1] $3 OFS} END {for (i in a) print "script", a i}' infile