I have an input notepad file as shown below:
sample input file:
vegetables and rates
kg rate total
Tomato 4 50 100
potato 2 60 120
Beans 3 80 240
Overalltotal: (100+120++240) = 460
I need to multiply the column 2 and column 3 and check the total if it is right and the overall total as well. If that's not right we need to print in the same file as an error message as shown below
enter code here
sample output file:
vegetables and rates
kg rate vegtotal
Tomato 4 50 200
potato 2 60 120
Beans 3 80 240
Overalltotal: (200+120++240) = 560
Error in calculations: Vegtotal for tomato is wrong: It should be 200 instead of 100 Overalltotal is wrong: It should be 560 instead of 460
Code so far:
for f in Date*.log; do
awk 'NR>1{ a[$1]=$2*$3 }{ print }END{ printf("\n");
for(i in a)
{ if(a[i]!=$4)
{ print i,"Error in calculations",a[i] }
} }' "$f" > tmpfile && mv tmpfile "$f";
done
It calculates the total but not comparing the values. How can I compare them and print to same file?
Input
Output
Explanation
Complex awk solution:
The output:
Details:
NF && NR>1 && $0!~/total:/
- considering veg lines (excuding header and total lines)r=$2*$3
- the result of product of the 2nd and 3rd fieldsv=(v!="")? v"+"r : r
- concatenating resulting product valuesveg_er
- the array containing erroneous vegs info (veg name, erroneous product value, and real product value)err_t+=$4
- accumulating erroneous total valuet+=r
- accumulating real total value$0~/total/ && err_t
- processing total line and error events