I am trying to write a script in which each row element will give the average of next N rows (including itself). I know how to do it with preceding rows like the Nth row will give the average of the preceding N rows. Here is the script for that

```
awk '
BEGIN{
       N = 5;
     }

     { 
       x = $2;
       i = NR % N;
       aveg += (x - X[i]) / N;
       X[i] = x;
       print $1, $2, aveg; 
     }' < file > aveg.txt

```

where file looks like this

```
     1       1
     2       2
     3       3
     4       4
     5       5
     6       6
     7       7
     8       8
     9       9
    10      10
    11      11
    12      12
    13      13
    14      14
    15      15
    16      16
    17      17
    18      18
    19      19
    20      20
    21      21
    22      22
    23      23
    24      24
    25      25
    26      26
    27      27
    28      28
    29      29
    30      30
    31      31
    32      32
    33      33
    34      34
    35      35
    36      36
    37      37
    38      38
    39      39
    40      40

```

I want that the first row has average of the next 5 elements i.e.

```
 (1+2+3+4+5)/5=3
 second row (2+3+4+5+6)/5=4
 third row  (3+4+5+6+7)/5=5

```

and so on. The rows should look like

```
    1        1       3  
    2        2       4
    3        3       5
    4        4       6   ...

```

Can it be done as simply as the script shown above? I was thinking of assigning the row value as the value of nth row below and then proceeding with the above script. But, unfortunately I am unable to assign the row value to some value down the file. Can someone help me to write this script and find the moving average. I am open to other commands in shell as well.