问题
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