AWK数组变量的级联 - 意外行为 [英] Concatenation of AWK array variables - unexpected behaviour
本文介绍了AWK数组变量的级联 - 意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
输入文件
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
它给人的输出
,orangesrs
,plumsesples
,nactariness
这样看来,字符串连接 A [$ 1] = A [$ 1],$ 2
是导致数组元素的原始值将被覆盖到一定程度上。我怎样才能开展这项拼接是否正确?
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?
顺便说一句,我得到的Centos相同的结果,和Mac OSX。
Incidentally, I get the same results on Centos, and Mac OSX.
推荐答案
您可以试试这个:
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发布后,我看到,这是一样的肯特公布,但没有资料为什么删除。
PS After posted it, I see that this is the same as Kent posted, but no info on why deleted.
这篇关于AWK数组变量的级联 - 意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文