Вопрос

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.

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:

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?

Это было полезно?

Решение

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

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.

Другие советы

awk can do associate array as well. Try this 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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top