使用 bash 求小数的平均值
如何取文件中写入的十进制值的平均值:TestFile as
Time to write: 0.000118000 sec
Time to write: 0.000119000 sec
Time to write: 0.000122000 sec
Wrong Soln:
以下仅打印零,即 0
awk '{sum+=$7}END{print sum/NR}' TestFile
How can I take average of decimal values written in a file: 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 i.e. 0
awk '{sum+=$7}END{print sum/NR}' TestFile
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该解决方案将以正确的行为目标进行计算:
This solution will target calculation at the correct lines:
编辑
因为您遇到了麻烦,并且似乎返回零,请尝试使用此
grep -oP "\d+\.\d+" testFile | awk -vx=0 '{x += $1} END {print x/NR}'
无论文件是否为双倍行距,这都将起作用。它只打印具有十进制数的文件的匹配项。并将其发送到 awk。
-P 标志是 perl 正则表达式。您可以使用 -E 执行相同的操作,但
\d+
匹配一个或多个数字,\.
匹配句点。一个。在正则表达式中具有特殊含义,需要转义,并且\d+
匹配一个或多个数字,因此将它们放在一起,'\d+\.\d+'
,你有一个十进制。最后,如果您继续使用科学记数法,您可以考虑 printf 来实现浮点记数
awk -vx=0 '{x += $4} END { printf ("%8.9f", x/NR) } testFile'
你可以指定一些更小的值,例如“%4.3f”,以仅打印小数点后的 4 个数字,相反,使用 %e 以科学记数法打印
更多在
awk< 中使用 printf
/code>
旧信息,请参见上面
awk -vx=0 '{x += $4} END {print x/NR}' testFile
输出:
每行将 $4(在测试文件中是数字)附加到 x。最后除以 x 即可得到行数。
如果您的文件确实是双倍行距,请先运行以下命令:
sed -i '/^$/d' testFile
以删除空白行。您可能需要考虑通过删除 -i 并执行类似sed '/^$/d' testFile > 之类的操作来不编辑 testFile newFile
甚至合并两个文件,并将 stdout 从
sed
传输到awk
sed '/^$/d' testFile | awk -vx=0 '{x += $4} END {print x/NR}'
如果返回 0,则您的 testFile 可能有问题。
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.
the -P flag is a perl regular expression. you could do the same with -E, but
\d+
matches one or more digits,\.
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.lastly, if you continue to get scientific notation you may consider printf to achieve floating point noation
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
More using printf in
awk
old information, see above
<hr>
awk -vx=0 '{x += $4} END {print x/NR}' testFile
which outputs:
for each line append $4, which in your test file is the number, to x. At the end divide x for number of lines.
if your file is really double spaced run the following first:
sed -i '/^$/d' testFile
to remove blank lines. you may want to consider not editing testFile in place by removing -i and doing something like thissed '/^$/d' testFile > newFile
or even combine the two files and pipe stdout from
sed
toawk
sed '/^$/d' testFile | awk -vx=0 '{x += $4} END {print x/NR}'
if this returns 0, you may have a problem with your testFile.