Count math using awk

Hi expert,

I have log :

TOTAL-TIME                :      2125264636
DATA-BYTES-DOWN           :   3766111307032
DATA-BYTES-UP             :    455032157567

DL = (3766111307032/2125264636)/1024 = 1.73
UL = (455032157567/2125264636)/1024 = 0.21

I want the result :

TOTAL = 1.94 

Anybody can help

Hello justbow,

Following may help you in same.

awk -F":" '/TOTAL-TIME/ {A=$2} !/TOTAL-TIME/ {COUNT+=(($2 / A) / 1024);} END{print "TOTAL= "COUNT}'  Input_file

Output will be as follows, this will work for given input data.

TOTAL= 1.93962

EDIT: Adding global solution if more than the given lines are there in input file.

awk -F":" '/TOTAL-TIME/ {A=$2} /DATA-BYTES-DOWN/ {X=(($2 / A) / 1024)} /DATA-BYTES-UP/ {Y=(($2 / A) / 1024); printf "%s %2.2f\n", "TOTAL =",  X+Y}'  Input_file

Following is a non oneliner form of solution.

awk -F":" '
                /TOTAL-TIME/ {A=$2}
                /DATA-BYTES-DOWN/ {X=(($2 / A) / 1024)}
                /DATA-BYTES-UP/ {Y=(($2 / A) / 1024);
                printf "%s %.2f\n", "TOTAL =",  X+Y}
          ' Input_file

Thanks,
R. Singh

Also try

awk -F':' '$1 ~ /TIME/ { t=$2 } $1 ~ /DOWN/ { d=$2 } $1 ~ /UP/ { u=$2 }
            END { a=d/t/1024; b=u/t/1024; printf "%s %2.2f\n", "TOTAL =", a+b }' log

Hello junior-helper,

If input file has more than one set of entries provided by user then above command will give only the last line value. Let's say following is the input file.

TOTAL-TIME                :      2125264636
DATA-BYTES-DOWN           :   3766111307032
DATA-BYTES-UP             :    455032157567
TOTAL-TIME                :      2128964636
DATA-BYTES-DOWN           :   376616327207032
DATA-BYTES-UP             :    455032123672567
TOTAL-TIME                :      21252647866
DATA-BYTES-DOWN           :   3766111307278387232
DATA-BYTES-UP             :    455032152376267
TOTAL-TIME                :      21252127236
DATA-BYTES-DOWN           :   376611113131032
DATA-BYTES-UP             :    4550321131313167

Then it will give output as follows.

awk -F':' '$1 ~ /TIME/ { t=$2 } $1 ~ /DOWN/ { d=$2 } $1 ~ /UP/ { u=$2 }
 END { a=d/t/1024; b=u/t/1024; printf "%s %2.2f\n", "TOTAL =", a+b }' Input_file
TOTAL = 226.40

So we can use following for it.

awk -F':' '$1 ~ /TIME/ { t=$2 } $1 ~ /DOWN/ { d=$2 } $1 ~ /UP/ { u=$2; a=d/t/1024; b=u/t/1024; printf "%s %2.2f\n", "TOTAL =", a+b;next }'  Input_file

Output will be as follows now.

TOTAL = 1.94
TOTAL = 381.48
TOTAL = 173074.31
TOTAL = 226.40

Thanks,
R. Singh

Hi RavinderSingh13,
basically, you are right. I tailored my command for the provided input though :wink:

By the way, (I know I falsely introduced it though) the first "2" in %2.2f is superfluous padding, because due to .2 it will never take effect, so %.2f should be used instead.