2010-04-21 83 views
2

我有一个文件包含在单个列中的数据..我必须找到每4行的总和并打印总和 也就是说,我必须计算从第4行的第0-3行总和的值的总和7,线8至11等的总和.....每N行的总和; awk

回答

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

如果你的文件有保留

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

第一个答案让我..Thanks很多 – 2010-04-21 07:05:52

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