I have a file containing N*10 lines, each line consisting of a number. I need to sum up every 10 lines and then print out an average for every such group. I know it's doable in awk, I just don't know how.
2 Answers
Try something like this:
$ cat input
1
2
3
4
5
6
2.5
3.5
4
$ awk '{sum+=$1} (NR%3)==0{print sum/3; sum=0;}' input
2
5
3.33333
(Adapt for 10-line blocks, obviously.)
-
2You could have used
seqto abstract away the test input:seq 50|awk '{sum += $1} (NR%10)==0{print sum/10; sum = 0;}'– mike3996Commented Dec 18, 2011 at 12:33 -
Hm, it doesn't seem to work in my case. Could the fact that I'm working on decimal values have anything to do with it?– gablinCommented Dec 18, 2011 at 13:02
-
I found what was wrong. My line didn't actually consist entirely of a number, but some textual strings before it. So in my case it should be
$4instead of$1. Now it's working. Thanks! =)– gablinCommented Dec 19, 2011 at 10:17
May be something like this -
[jaypal:~/Temp] seq 20 > test.file
[jaypal:~/Temp] awk '
{sum+=$1}
(NR%10==0){avg=sum/10;print $1"\nTotal: "sum "\tAverage: "avg;sum=0;next}1' test.file
1
2
3
4
5
6
7
8
9
10
Total: 55 Average: 5.5
11
12
13
14
15
16
17
18
19
20
Total: 155 Average: 15.5
If you don't want all lines to be printed then the following would work.
[jaypal:~/Temp] awk '
{sum+=$1}
(NR%10==0){avg=sum/10;print "Total: "sum "\tAverage: "avg;sum=0;next}' test.file
Total: 55 Average: 5.5
Total: 155 Average: 15.5