Hi
I have attached txt file as input,
and i'm able to calculate sum of columns at the end but the format of sum is not coming up right.
awk -F"," '{for (i=4;i<=NF;i++) sum+=$i}{print}; END { sum[1]="Total:"; for (i=1;i<=NF;i++) {printf sum ","} print "\n"}' input.txt
check the o/p file, at the Total: line I need to print exact sum of each columns, not 129102+E08 etc.
I even tried to printf "%10.4f" and it's still not working.
can anyone suggests how to print sum of columns with exact amount...
Convert this txt to Excel for better viewing....
RudiC
January 26, 2016, 10:01am
2
Well, "%10.4f"
is not enough; it allows for 5 digits before the period. If the value is too large, awk
print
switches to the "g" scientific/engineering format. Your results (e.g. 1.29102e+08) are significantly larger. Try e.g. "%12.2f"
.
---------- Post updated at 16:01 ---------- Previous update was at 15:59 ----------
Or, just "%f"
might work ...
Hi Rudy,
No it's not working
can you tell me, what I'm doing wrong here,
awk -F"," '{for (i=4;i<=NF;i++) sum+=$i}{print}; END { sum[1]="Total:"; for (i=1;i<=NF;i++) {printf("%15.5f%s", sum, ",")} print "\n"}' inputfile
even %f doesn't print right number.
using this I don't have Total line in my bottom of file including I'm missing right numbers.
awk -F"," '{for (i=4;i<=NF;i++) sum+=$i}{print}; END { sum[1]="Total:"; for (i=1;i<=NF;i++) {printf sum ","} print "\n"}' input.txt
if I use this, then I have total but one screw up is the format of number.
Can you assist me.
RudiC
January 26, 2016, 11:05am
4
What exactly is wrong with it? Except that it prints three "0.000000" columns in the begin of the last line which is OK as you print a string with a numerical format...
How about END {printf "Total:,,,"; for (i=4;i<=NF;i++)...
Hi Rudi,
The problem is with sum[i], it doesn't print the big decimal number, no matter how big I extend %f .
RudiC
January 26, 2016, 1:26pm
6
This is what it prints for me:
... {printf("%.2f,", sum)} ...
Total:,,,129102083.37,129310134.67,130394794.10,132169591.38,134112515.47,133504487.51,132898230.90,135716155.12,140092809.14,140656362.70,...
What's wrong with it?
Yes, the text fields should be left out. The following works with several awk versions ( even the Solaris /bin/awk -> oawk )
awk -F"," 'NR>1 {for (i=4;i<=NF;i++) sum+=$i; nf=NF} {print} END {printf "Total:,,"; for (i=4;i<=nf;i++) {printf ",%f", sum} print ""}' input.txt