问题
Input file
steve,apples
steve,oranges
john,pears
john,oranges
mary,bananas
steve,plums
mary,nactarines
I want to get output like this:
steve:apples,oranges,plums
john:pears,oranges
mary:bananas,nectarines
Here is the one liner I have been trying to get to work:
awk -F, '{if(a[$1])a[$1]=a[$1]","$2; else a[$1]=$2;}END{for (i in a)print i ":" a[i];}' OFS=, inputfile
The output it gives is
,orangesrs
,plumsesples
,nactariness
It would appear that the string concatenation a[$1]=a[$1]","$2
is resulting in the original value of the array element to be overwritten to some degree. How can I carry out this concatenation correctly?
Incidentally, I get the same results on Centos, and Mac OSX.
回答1:
You can try 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, I see that this is the same as Kent posted, but no info on why deleted.
来源:https://stackoverflow.com/questions/24433376/concatenation-of-awk-array-variables-unexpected-behaviour