Averaging in increments using awk & head/tail

Hi, I only have a very limited understanding and experience with writing code and I was hoping I could get some help.
I have a dataset of two columns (txt format, numbers in each row separated by a tab)
Eg.
1 5
2 5
3 6
4 7
5 6
6 6
7 5
8 3
9 2
10 1

I want to get the average of column 2 for the first three numbers - so 5,5,6 - then move down one position for the average of the next three - so 5,6,7 - then average the next lot - 6,7,6 - etc, moving down the whole column. So then I'll end up with a column of averages.

5.33
6
6.33
6.33
...etc

This is my code so far...

 
head -3 datafilename.txt | tail -3 | awk '{sum +=$2} END {print sum/3}'

...which will give me the average of the first bracket of three numbers.
I've been trying to use a for loop to move the averaging down the column but I'm having difficulty making it work.
Something like...

 
BEGIN {for (i=1; i++)} head -$i datafilename.txt | tail -3 | awk '{sum +=$2} END {print sum/3}'

But I have no idea really (you can probably tell).

Any suggestions would be greatly appreciated,
Emred Skye.

cut -f2 -d" " file| paste - - -|sed -r 's/[ \t]+/+/g'| sed 's|.*|echo "scale=2;(&)\/3"\|bc|' |sh 2>/dev/null

Hi

awk '{printf "%d ",$2}' file | awk '{while(j+2!=NF){for(i=j;i<j+3;i++)sum+=$i;print sum/3;sum=0;j++;}}' j=1

Guru.

1 Like
awk '{printf "%d ",$2}' file |awk '{for (i=3;i<=NF;i++) printf "%.2f\n", ($(i-1)+$(i-2)+$i)/3}'
1 Like

Thanks for the quick responses! I couldn't get kurumi's code to work (and I do not understand it) but Guru's and rdcwayx's both work.

Guru if you are able to explain, can you tell me why you need ---> while(j+2!=NF)

Hi
J+2 is needed so that you stop the processing while encountering the third last line itself.

Guru.