Reputation: 113
I am trying to print a simple report with the awk command and with and some calculations. This is the input file:
1 Syed-Yamin 3 500
2 Ilia-Nika 4 400
3 Mike-Ro 5 300
4 Witold-Ryb 2 200
5 Farhan-F 1 500
In the report I want to print the 1st column, the 2nd column and the calculation result of multiplication of the 3rd and 4th columns for each row. Also, I want to print on the bottom the total of the all multiplications from each row. I am getting some extra lines in the output and would like to clean them up. So the end result should look like that:
1 Syed-Yamin 1500
2 Ilia-Nika 1600
3 Mike-Ro 1500
4 Witold-Ryb 400
5 Farhan-F 500
Total amount = $5500
awk 'BEGIN {total=0;}
{print "$1, $2, ($3 * $4)";}
total=total+($3 * $4)
END {print "Total Amount = $", total;}' input
awk print with lots of extra lines
Upvotes: 2
Views: 352
Reputation: 67507
here I fixed for you...
$ awk -v OFS='\t' '{$3 *= $4; NF--; total += $3}1
END {print "","Total Amount =", "$"total}' file |
column -ts$'\t'
1 Syed-Yamin 1500
2 Ilia-Nika 1600
3 Mike-Ro 1500
4 Witold-Ryb 400
5 Farhan-F 500
Total Amount = $5500
perhaps better formatted this way
$ awk '{printf "%d\t%s\t%5d\n",$1,$2,$3*=$4; total+=$3}
END {print "\tTotal Amount =\t$"total}' file |
column -ts$'\t'
1 Syed-Yamin 1500
2 Ilia-Nika 1600
3 Mike-Ro 1500
4 Witold-Ryb 400
5 Farhan-F 500
Total Amount = $5500
Upvotes: 2