是否可以通过在第二列中添加名称来打印第一列中的唯一名称,如下所示?提前谢谢!
输入
tony singapore
johnny germany
johnny singapore
输出
tony singapore
johnny germany;singapore
是否可以通过在第二列中添加名称来打印第一列中的唯一名称,如下所示?提前谢谢!
输入
tony singapore
johnny germany
johnny singapore
输出
tony singapore
johnny germany;singapore
$ 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
试试这个单行:
awk '{a[$1]=$1 in a?a[$1]";"$2:$2}END{for(x in a)print x, a[x]}' file
这是一个神秘的 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