1

是否可以通过在第二列中添加名称来打印第一列中的唯一名称,如下所示?提前谢谢!

输入

tony  singapore
johnny  germany
johnny  singapore

输出

tony  singapore
johnny  germany;singapore
4

3 回答 3

1
$ awk '{name2vals[$1] = name2vals[$1] sep[$1] $2; sep[$1] = ";"} END { for (name in name2vals) print name, name2vals[name]}' file
johnny germany;singapore
tony singapore
于 2013-07-04T13:44:24.643 回答
1

试试这个单行:

awk '{a[$1]=$1 in a?a[$1]";"$2:$2}END{for(x in a)print x, a[x]}' file
于 2013-07-04T13:43:31.870 回答
0

这是一个神秘的 sed 变体:

script.sed 的内容

$ cat script.sed 
:a                        # Create a label called loop
$!N                       # If not last line, append the line to pattern space
s/^(([^ ]+ ).*)\n\2/\1;/  # If first column is same append second column to it separated by ;
ta                        # If the last substitution was successful loop back
P                         # Print up to the first \n of the current pattern space
D                         # Delete from current pattern space, up to the \n character

执行:

$ cat file
tony  singapore
johnny  germany
johnny  singapore

$ sed -rf script.sed file
tony  singapore
johnny  germany; singapore
于 2013-07-05T01:35:57.297 回答