hosselausso
hosselausso

Reputation: 1077

How to sum up every nth line in awk?

I want to output the sum of every N lines, for example, every 4 lines:

cat file
1
11
111
1111
2
22
222
2222
3
33
333
3333

The output should be:

6 #(1+2+3)
66 #(11+22+33)
666 #(111+222+333)
6666 #(1111+2222+3333)

How can I do this with awk?

Upvotes: 2

Views: 924

Answers (1)

hek2mgl
hek2mgl

Reputation: 158040

Basically you can use the following awk command:

awk -vN=4 '{s[NR%N]+=$0}END{for(i=0;i<N;i++){print s[i]}}' input.txt

You can choose N like you wish.

Output:

6666
6
66
666

But you see, the output isn't sorted as expected when iterating through an awk array. You can fix this by shifting the line number by -1:

awk -vN=4 '{s[(NR-1)%N]+=$0}END{for(i=0;i<N;i++){print s[i]}}' a.txt

Output:

6
66
666
6666

Upvotes: 2

Related Questions