linux - Taking average of decimal number using bash -
how can take average of decimal values written in file: testfile as
time write: 0.000118000 sec time write: 0.000119000 sec time write: 0.000122000 sec
wrong soln:
following prints 0 i.e. 0
awk '{sum+=$7}end{print sum/nr}' testfile
edit
since having trouble, , seem return 0 try using this
grep -op "\d+\.\d+" testfile | awk -vx=0 '{x += $1} end {print x/nr}'
this work if file double spaced or not. prints match of file has decimal number. , sends awk.
the -p flag perl regular expression. same -e, \d+
matches 1 or more digits, \.
matches period. . has special meaning in regular expressions , need escaped , \d+
matches 1 or more digits put together, '\d+\.\d+'
, have decimal.
lastly, if continue scientific notation may consider printf achieve floating point noation
awk -vx=0 '{x += $4} end { printf ("%8.9f", x/nr) } testfile'
you can specifiy smaller "%4.3f" print 4 numbers after decimial, conversely, use %e print in scientific notation
more using printf in awk
old information, see above <hr>
awk -vx=0 '{x += $4} end {print x/nr}' testfile
which outputs:
0.000119667
for each line append $4, in test file number, x. @ end divide x number of lines.
if file double spaced run following first:
sed -i '/^$/d' testfile
remove blank lines. may want consider not editing testfile in place removing -i , doing sed '/^$/d' testfile > newfile
or combine 2 files , pipe stdout sed
awk
sed '/^$/d' testfile | awk -vx=0 '{x += $4} end {print x/nr}'
if returns 0, may have problem testfile.
Comments
Post a Comment