How to add values of duplicate keys in associative arrays, using Shell Script? -


i'm having trouble removing duplicate keys lower value.

i've used while loop loop through file while read key value.

the original text file looks this:

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

this output 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 values of same keys want remove key lower value.

my desired output this:

electron 5 hadron 7 meson 18 neutron 20 proton 15 

is there way of returning higher value , finishing off script sort?

using bash version 4 -- sh not have associative arrays

declare -a sum  while read key value; ((sum[$key] += value)); done <file  key in "${!sum[@]}"; echo $key ${sum[$key]}; done 
proton  15 neutron  20 hadron  7 electron  5 meson  18 

associative array keys have no natural ordering. can pipe loop sort or sort -k2n if wish.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -