Sharat Chandra
Sharat Chandra

Reputation: 4544

Sum of every N lines ; awk

I have a file containing data in a single column .. I have 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 .....

Upvotes: 2

Views: 4309

Answers (2)

ghostdog74
ghostdog74

Reputation: 342363

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

Upvotes: 6

Dennis Williamson
Dennis Williamson

Reputation: 360065

$ 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

Upvotes: 1

Related Questions