Concatenation of AWK array variables - unexpected behaviour

安稳与你 提交于 2020-01-05 12:09:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!