[英]Taking average of decimal number using bash
How can I take average of decimal values written in a file: TestFile as如何取写入文件中的十进制值的平均值:TestFile as
Time to write: 0.000118000 sec
Time to write: 0.000119000 sec
Time to write: 0.000122000 sec
Wrong Soln:错误的索尔:
Following prints just zero ie 0以下仅打印零,即 0
awk '{sum+=$7}END{print sum/NR}' TestFile
This solution will target calculation at the correct lines:此解决方案将针对正确的行进行计算:
awk '/Time to write/ {sum+=$4; count++} END {print "avg:", sum/count}' data.txt
EDIT
编辑
since you are having trouble, and seem to return zero try using this因为你遇到了麻烦,并且似乎返回零尝试使用这个
grep -oP "\d+\.\d+" testFile | awk -vx=0 '{x += $1} END {print x/NR}'
this will work if the file is double spaced or not.如果文件是双倍行距的,这将起作用。 it only prints the match of a file that has as decimal number.
它只打印具有十进制数字的文件的匹配项。 and sends it to awk.
并将其发送到 awk。
the -P flag is a perl regular expression. -P 标志是 perl 正则表达式。 you could do the same with -E, but
\d+
matches one or more digits, \.
你可以用 -E 做同样的事情,但是
\d+
匹配一个或多个数字, \.
matches a period.匹配一个句点。 a.
一个。 has special meaning in regular expressions and need to be escaped and
\d+
matches one or more digits so put that together, '\d+\.\d+'
, you have a decimal.在正则表达式中具有特殊含义,需要转义,并且
\d+
匹配一个或多个数字,因此将它们放在一起, '\d+\.\d+'
,你有一个小数。
lastly, if you continue to get scientific notation you may consider printf to achieve floating point noation最后,如果您继续获得科学记数法,您可以考虑使用 printf 来实现浮点记数法
awk -vx=0 '{x += $4} END { printf ("%8.9f", x/NR) } testFile'
you can specifiy something smaller like "%4.3f" to print only 4 numbers after a decimial, Conversely, use %e to print in scientific notation你可以指定一些更小的东西,比如“%4.3f”,在小数点后只打印 4 个数字,相反,使用 %e 以科学记数法打印
More using printf in awk
更多在 awk 中使用
awk
old information, see above <hr>
旧资料,见上
<hr>
awk -vx=0 '{x += $4} END {print x/NR}' testFile
which outputs:输出:
0.000119667
0.000119667
for each line append $4, which in your test file is the number, to x.对于每一行 append $4,在你的测试文件中是数字,到 x。 At the end divide x for number of lines.
最后除以 x 为行数。
if your file is really double spaced run the following first:如果您的文件真的是双倍行距,请先运行以下命令:
sed -i '/^$/d' testFile
to remove blank lines. sed -i '/^$/d' testFile
删除空行。 you may want to consider not editing testFile in place by removing -i and doing something like this sed '/^$/d' testFile > newFile
您可能要考虑不通过删除 -i 并执行类似
sed '/^$/d' testFile > newFile
来编辑 testFile
or even combine the two files and pipe stdout from sed
to awk
甚至将这两个文件和 pipe 标准输出从
sed
到awk
sed '/^$/d' testFile | awk -vx=0 '{x += $4} END {print x/NR}'
if this returns 0, you may have a problem with your testFile.如果返回 0,则您的 testFile 可能有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.