开发者

Sum of every N lines ; awk

I have a file containing data in a single column .. I ha开发者_StackOverflow中文版ve to find the sum of every 4 lines and print the sum That is, I have to compute sum of values from 0-3rd line sum of line 4 to 7,sum of lines 8 to 11 and so on .....


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

if your file has 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


$ 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜