Sum of all N lines; AWK

I have a file that contains data in one column. I need to find the sum of every 4 lines and print the sum.That is, I have to calculate the sum of values ​​from 0-3 lines of lines from lines 4 to 7, the sum of lines from 8 to 11, etc ...

+2


a source to share


2 answers


awk '{s+=$1}NR%4==0{print s;s=0}' file

      

if your file remains



$ cat file
1
2
3
4
5
6
7
8
9
10

$ awk '{s+=$1}NR%4==0{print s;t+=s;s=0}END{print "total: ",t;if(s) print "left: " s}' file
10
26
total:  36
left: 19

      

+5


a source


$ cat file
1
2
3
4
5
6
7
8
$ awk '{subtotal+=$1} NR % 4 == 0 { print "subtotal", subtotal; total+=subtotal; subtotal=0} END {print "TOTAL", total}' file
subtotal 10
subtotal 26
TOTAL 36

      



+1


a source







All Articles