如何使用Shell脚本在关联数组中添加重复键的值?

时间:2021-08-04 12:19:28

I'm having trouble removing duplicate keys with the lower value.

我在删除值较低的重复键时遇到问题。

I've used a while loop to loop through the file with while read key value.

我使用了while循环来循环读取文件,同时读取键值。

The Original text file looks like this:

原始文本文件如下所示:

meson 6
electron 5
meson 12
neutron 10
proton 5
hadron 7
neutron 10
proton 2
proton 8

This is my output so far using associative arrays in shell:

到目前为止,这是我在shell中使用关联数组的输出:

electron 5
hadron 7
meson 18
meson 6
neutron 10
neutron 20
proton 15
proton 5
proton 7

I summed up the values of the same keys but I want to remove the key with the lower value.

我总结了相同键的值,但我想删除值较低的键。

My desired output is this:

我想要的输出是这样的:

electron 5
hadron 7
meson 18
neutron 20
proton 15

Is there a way of returning the higher value only and then finishing off the script with sort?

有没有办法只返回更高的值,然后用排序完成脚本?

2 个解决方案

#1


1  

Using bash version 4 -- sh does not have associative arrays

使用bash版本4 - sh没有关联数组

declare -A sum

while read key value; do ((sum[$key] += value)); done <file

for key in "${!sum[@]}"; do echo $key ${sum[$key]}; done
proton  15
neutron  20
hadron  7
electron  5
meson  18

Associative array keys have no natural ordering. You can pipe that for loop into sort or sort -k2n if you wish.

关联数组键没有自然顺序。如果您愿意,可以将for循环管道排序或排序-k2n。

#2


0  

awk can do associate array as well. Try this awk

awk也可以关联数组。试试这个awk

awk '!($1 in a) || a[$1] < $2{a[$1]=$2; next} END {for (i in a) print i, a[i]}' file
neutron 10
electron 5
proton 8
hadron 7
meson 12

#1


1  

Using bash version 4 -- sh does not have associative arrays

使用bash版本4 - sh没有关联数组

declare -A sum

while read key value; do ((sum[$key] += value)); done <file

for key in "${!sum[@]}"; do echo $key ${sum[$key]}; done
proton  15
neutron  20
hadron  7
electron  5
meson  18

Associative array keys have no natural ordering. You can pipe that for loop into sort or sort -k2n if you wish.

关联数组键没有自然顺序。如果您愿意,可以将for循环管道排序或排序-k2n。

#2


0  

awk can do associate array as well. Try this awk

awk也可以关联数组。试试这个awk

awk '!($1 in a) || a[$1] < $2{a[$1]=$2; next} END {for (i in a) print i, a[i]}' file
neutron 10
electron 5
proton 8
hadron 7
meson 12