[英]Using awk to calculate an average of numbers
I have a file named test.txt
with the following: 我有一个名为
test.txt
的文件,其中包含以下内容:
10
200
3000
=======
4
5
=======
I need to write an awk script to take the text in this file as input into the awk script and output: 我需要编写一个awk脚本以将该文件中的文本作为输入到awk脚本并输出:
10
200
3000
Average 1070.00
4
5
Average 4.50
I wrote my script like this: 我这样写我的脚本:
{while($1!~"=======") s+=$1;}
{print "Average ", s}
Every time I run this code, I use: 每次运行此代码时,我都会使用:
awk -f awrp4 test.txt
But it crashes. 但是它崩溃了。 I don't know what I'm doing wrong.
我不知道我在做什么错。 I'm a beginner and trying to learn about the awk function so I apologize if this seems rather simple.
我是一个初学者,尝试学习awk函数,所以如果这看起来很简单,我深表歉意。 Any help is welcome.
欢迎任何帮助。
Using GNU awk, you can write: 使用GNU awk,您可以编写:
gawk '
BEGIN {FS = "\n"; RS = "\n=+\n"}
NF > 0 {
sum = 0
for (i=1; i<=NF; i++) {
print $i
sum += $i
}
printf "Average %.2f\n", sum/NF
}
' file
Certainly nothing wrong with Glenn's solution, but it might be a bit advanced for you. Glenn的解决方案当然没错,但是对您来说可能有点高级。 Maybe this is better suited:
也许这更适合:
{
if ($1 == "=======") {
print "\nAverage " s/i "\n";
s=0;
i=0;
} else {
print $1;
s += $1;
i += 1;
}
}
As I mentioned in the comments, the nature of awk
is to loop through every line of a text file. 正如我在评论中提到的那样,
awk
的本质是遍历文本文件的每一行。 Unless you're doing some post-processing or working with arrays, a while
loop probably isn't of much use. 除非您要进行一些后处理或使用数组,否则
while
循环可能没什么用。
awk '$1~/^[[:digit:]]/ {i++; sum+=$1; print $1} $1!~/[[:digit:]]/ {print "Average", sum/i; sum=0;i=0}' file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.