Friday, 15 February 2013

string - Concatenation of AWK array variables - unexpected behaviour -



string - Concatenation of AWK array variables - unexpected behaviour -

input file

steve,apples steve,oranges john,pears john,oranges mary,bananas steve,plums mary,nactarines

i want output this:

steve:apples,oranges,plums john:pears,oranges mary:bananas,nectarines

here 1 liner have been trying work:

awk -f, '{if(a[$1])a[$1]=a[$1]","$2; else a[$1]=$2;}end{for (i in a)print ":" a[i];}' ofs=, inputfile

the output gives

,orangesrs ,plumsesples ,nactariness

it appear string concatenation a[$1]=a[$1]","$2 resulting in original value of array element overwritten degree. how can carry out concatenation correctly?

incidentally, same results on centos, , mac osx.

you can seek this:

awk -f, '{a[$1]=(a[$1]?a[$1]fs$2:$2)} end {for (i in a) print i":"a[i]}' file mary:bananas,nactarines john:pears,oranges steve:apples,oranges,plums

ps after posted it, see same kent posted, no info on why deleted.

string awk concatenation

No comments:

Post a Comment