0

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.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
linuxman
  • 61
  • 5

1 Answers1

0

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
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93