简体   繁体   English

使用awk计算数字的平均值

[英]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
  • The first part checks if the first character from column 1 is a digit, if so then increment the counter 'i' and add that record(number) to sum. 第一部分检查第1列中的第一个字符是否为数字,如果是,则增加计数器'i'并将该记录(数字)相加。
  • The second part is to skip any record that does not start with a digit, and then you print the average by dividing sum/i, finally reset counter and sum to 0. 第二部分是跳过任何不以数字开头的记录,然后通过将sum / i除以打印平均值,最后重置计数器并将sum设为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM