How to add using awk command for a group?

hi all

below is the input file contains a code followed by amount

input file

345,5.86
346,20.58
399,10.00
400,12.00

i need the output in the following way outputfile

totalsumof345and346,26.44
totalsumof399and400,22.00

i have the awk command to add of similar group ..can we do the add for two different groups using awk..?

thanks in advance

What defines a "group", and what separates two groups? And, when to apply the "and" and when the "," in the output?

hi ,
sorry i modified the input and output.

group is the code values like 345,346...

i have the input file format constant as stated above but i need to combine and need to get the total as shown in outputfile

That does not answer the question RudiC asked.

How do you determine that 345 and 346 are "similar groups" and that 399 is not "similar" to 345 or 346?

hi,
I generated the report which i gave as input file and codes(345,346,399,400) in it are constant the amount will vary when i generate the input reports .Now i have to create the sum as shown in output file ...by passing the inputfile to the script to generate the output file.. Hope it clear ..:slight_smile:

Why don't you combine 345 and 400 into one group, and 346 and 399 into another? Are groups always groups of two? Or three?

1 Like

hi Rudic,
the input file will be constant,amount may varies and the add will be on group of 2...

as per my requirement i have to add 345,346 and 399,400 ...is it possible to perform add ..? if yes could you please help..?

Thanks in advance

It is easy to add the values for the 345/346 and 399/400 groups. Where would a line like 513,7.19 fit in? If it came in line No. 1, 2, 3, 4, or 5?

Hello hemanthsaikumar,

Could you please try following and let me know if this helps you.

awk -F, '($1 == 345 || $1 == 346){A=A+$2} ($1 == 399 || $1 == 400){B=B+$2} END{if(A){print "Sum of group 345 and 346= " A};if(B){print "Sum of group 399 and 400= " B}}'  Input_file

Output will be as follows.

Sum of group 345 and 346= 26.44
Sum of group 399 and 400= 22

But again it will look for groups of 345, 346 and 399, 400 only. Let us know with complete details if your requirement differs from this code.

Thanks,
R. Singh

As iam generating that input file no codes will be their other than that 4 codes.. so their is no chance of new codes or increment in records...

so how can we add them using awk or any other command ..? please help

awk -F, 'NR%2 {split ($0, L); next} {printf "totalsumof%sand%s,%.2f\n", L[1], $1, L[2]+$2}' file4
totalsumof345and346,26.44
totalsumof399and400,22.00

And, as RavinderSingh13 already stated, don't come back complaining that that input file has changed!