Lucas
Lucas

Reputation: 134

How to do calculations over lines of a file in awk

I've got a file that looks like this:

88.3055
45.1482
37.7202
37.4035
53.777

What I have to do is isolate the value from the first line and divide it by the values of the other lines (it's a speedup calculation). I thought of maybe storing the first line in a variable (using NR) and then iterate over the other lines to obtain the values from the divisions. Desired output is:

1,9559
2,3410
2,3608
1,6420

UPDATE

Sorry Ed, my mistake, the desired decimal point is .

I made some small changes to Ed's answer so that awk prints the division of 88.3055 by itself and outputs it to a file speedup.dat:

awk 'NR==1{n=$0} {print n/$0}' tavg.dat > speedup.dat

Is it possible to combine the contents of speedup.dat and the results from another awk command without using intermediate files and in one single awk command?

First command:

awk 'BEGIN { FS = \"[ \\t]*=[ \\t]*\" } /Total processes/ { if (! CP) CP = $2 } END {print CP}' cg.B.".n.".log ".(n == 1 ? ">" : ">>")." processes.dat

This first command outputs:

1
2
4
8
16

Paste of the two files:

paste processes.dat speedup.dat > prsp.dat

which gives the now desired output:

1   1
2   1.9559
4   2.34107
8   2.36089
16  1.64207

Upvotes: 1

Views: 76

Answers (2)

karakfa
karakfa

Reputation: 67497

awk '{if(n=="") n=$1; else print n/$1}' inputFile

Upvotes: -1

Ed Morton
Ed Morton

Reputation: 203483

$ awk 'NR==1{n=$0;next} {print n/$0}' file
1.9559
2.34107
2.36089
1.64207

$ awk 'NR==1{n=$0;next} {printf "%.4f\n", n/$0}' file
1.9559
2.3411
2.3609
1.6421

$ awk 'NR==1{n=$0;next} {printf "%.4f\n", int(n*10000/$0)/10000}' file
1.9559
2.3410
2.3608
1.6420

$ awk 'NR==1{n=$0;next} {x=sprintf("%.4f",int(n*10000/$0)/10000); sub(/\./,",",x); print x}' file
1,9559
2,3410
2,3608
1,6420

Normally you'd just use the correct locale to have . or , as your decimal point but your input uses . while your output uses , so I don't think that's an option.

Upvotes: 3

Related Questions