我有这个输入:
Fred apples 20
Susy oranges 5
Mark watermellons 12
Robert pears 4
Robert oranges 17
Terry oranges 9
Lisa peaches 7
Susy oranges 12
Mark grapes 39
Anne mangoes 7
Greg pineapples 3
Oliver rockmellons 2
Betty limes 14
我想要这样的输出:
Anne:
mangoes 7
Oliver:
rockmellons 2
Greg:
pineapples 3
Mark:
watermellons 12
grapes 39
Terry:
oranges 9
Susy:
oranges 17
Lisa:
peaches 7
Fred:
apples 20
Robert:
oranges 17
pears 4
Betty:
limes 14
我正在尝试使用 awk 命令来完成此操作。我的代码如下所示:
{
lines[$1] = (lines[$1] ? lines[$1] "\n " $2 " " $3 : $1 ":\n " $2 " " $3)
}
END {
for (line in lines) print lines[line]
}
我要比较第二列中的重复项并对数字求和。
答案1
使用 GNU awk,它具有数组的数组(可能需要 gawk 版本 4)
gawk '
NF { n[$1][$2] += $3 }
END {
for (name in n) {
print name ":"
for (fruit in n[name])
printf "%16s %2d\n", fruit, n[name][fruit]
}
}
'
答案2
如果您不介意对输出进行排序,您可以跟踪当前人和当前水果,并求和直到发生变化:
#!/usr/bin/awk -f
NF {
if (who != $1) {
if (count > 0) {
printf "%16s %2d\n", fruit, count
}
who = $1
printf "%s:\n", who
fruit = ""
count = 0
}
if (fruit != $2) {
if (count > 0) {
printf "%16s %2d\n", fruit, count
}
fruit = $2
count = $3
} else {
count += $3
}
}
END {
printf "%16s %2d\n", fruit, count
}
喂这个sort -k1,1 -k2,2
:
sort -k1,1 -k2,2 file.txt | ./script.awk