bash - Best to way to add up numbers by ids -
suppose have file, has 2 columns.
12,1 12,2 11,3 11,2
i want add second column first column. output should this
12,3 11,5
is there easy way on linux environments (on command line)?
$ cat file 12,1 12,2 11,3 11,2
here awk
approach:
$ awk -f, '$1 { a[$1]+=$2 } end { (i in a) { printf "%s,%d\n", i, a[i] } }' file 11,5 12,3
and here 1 in bash
:
$ cat ./id.sh #!/bin/bash ifs=',' while read id value; [ -n "${id}" ] || continue (( a[id] += value )) done < file id in "${!a[@]}"; echo "${id},${a[${id}]}" done $ ./id.sh 11,5 12,3
they both work same principle - read line line field/input separator set ,
, assemble array indexed first column - values of second column summed up. when hard work done, print array back.
Comments
Post a Comment