使用awk
(除非您知道或想学习 Perl 或 Python):
awk '{ sum[$1,0] += $2; sum[$1,1] += $3; sum[$1,2] += $4; names[$1] = 1; }
END { for (name in names)
printf "%s %d, %d, %d\n", name, sum[name,0], sum[name,1], sum[name,2];
}' <<EOF
alma-court, 1, 0, 8
alma-court, 4, 2, 24
atlantic-house, 99, 1, 340
diamond, 2, 2, 16
iminds-zuiderpoort, 0, 1, 0
north-plaza, 18, 3, 718
north-plaza, 90, 2, 19
EOF
输出:
iminds-zuiderpoort, 0, 1, 0
alma-court, 5, 2, 32
north-plaza, 108, 5, 737
atlantic-house, 99, 1, 340
diamond, 2, 2, 16
如果您希望名称按特定顺序排列,请对输出进行排序。请注意,名称包含尾随逗号,因此打印格式不会在名称后添加逗号。
纯bash
(4.x) 实现
{
declare -A sum
declare -A names
IFS=,
while read name v1 v2 v3
do
names[$name]="$name"
((sum[${name}1] += $v1))
((sum[${name}2] += $v2))
((sum[${name}3] += $v3))
done
for name in "${names[@]}"
do
printf "%s, %d, %d, %d\n" $name ${sum[${name}1]} ${sum[${name}2]} ${sum[${name}3]}
done
} <<EOF
alma-court, 1, 0, 8
alma-court, 4, 2, 24
atlantic-house, 99, 1, 340
diamond, 2, 2, 16
iminds-zuiderpoort, 0, 1, 0
north-plaza, 18, 3, 718
north-plaza, 90, 2, 19
EOF
输出:
diamond, 2, 2, 16
atlantic-house, 99, 1, 340
north-plaza, 108, 5, 737
alma-court, 5, 2, 32
iminds-zuiderpoort, 0, 1, 0
幸运的是,awk
和bash
脚本的输出是相同的,给出或接受数据的排序顺序。
该bash
脚本使用关联数组,这是 4.x 的一个特性,在3.xbash
中不存在。bash