How to sum numbers by a specific word separated by semi colon in bash [duplicate]

Home / Uncategorized / How to sum numbers by a specific word separated by semi colon in bash [duplicate]

Question:
This question already has an answer here:GROUP BY/SUM from shell 5 answers
How can I sum values in column based on the value in another column? 5 answers

To be more specific on the path for instance i have file as below;

file.txt

apple;10;
tomato;5;
apple;5;
banana;10;
banana;5;
tomato;10;
banana;10;
apple;5;
I want to sum numbers by item using bash as a result ;

file.output

apple;20;
banana;25;
tomato;15;
Another word is i need to simplify the file. How can achieve this kind of output as a separate file in bash ?

Thanks in advance.


Answer:
try following awk, if you need output in same sequence as Input_file then following may help you in same.
awk -F";" ‘!a[$1]{b[++i]=$1} {a[$1]+=$2;} END{for(j=1;j<=i;j++){print b[j] FS a[b[j]] FS}}' Input_file Output will be as follows. apple;20; tomato;15; banana;25; If you don't bother about sequence as per your Input_file then you could simply try following:awk -F";" '{a[$1]+=$2;} END{for(i in a){print i FS a[i] FS}}' Input_file Read more

Leave a Reply

Your email address will not be published. Required fields are marked *