Awk: substituting each n lines with their average, for each column

大城市里の小女人 提交于 2019-12-11 19:43:54

问题


How can I substitute each n lines of a file with their average using awk?

This question answer perfectly, except for the fact that it handles only one column and the 3 is not parametrized: How to sum up every 10 lines and calculate average using AWK?

basically I would like to take a file like this

1     1
2     1
3     1
4     1
5     1
6     1
2.5   2.0
3.5   2.0
4     2.0

and obtain something like this:

2     1   
5     1
3.33  2.0

回答1:


Here's a complete shell script:

awk -v count=3 '
    {
        if ( NF > tot_col )
            tot_col = NF;

        cur = 1;
        while ( cur <= NF )
        {
            sums[cur] += $cur;
            cur++;
        }

        if ( ( NR % count ) == 0 )
        {
            cur = 1;
            while ( cur <= tot_col )
            {
                printf("%0.2f ", sums[cur] / count);
                cur++;
            }

            print "";

            delete sums;
            tot_col = 0;
        }
    }' "$@"



回答2:


$ awk -v rows=3 '{c1+=$1; c2+=$2} (NR%rows)==0{printf "%.2f %.2f\n", c1/3, c2/3; c1=0; c2=0}' input
2.00 1.00
5.00 1.00
3.33 2.00


来源:https://stackoverflow.com/questions/18650126/awk-substituting-each-n-lines-with-their-average-for-each-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!