-2

I want to sum two rows until end of file:

1 2 3 4
0 1 2 3
0 4 5 6
2 3 5 6

Output should be

1 3 5 7
2 7 10 12

I have tried the following, but it only works for the 1st row

awk '{s+=$1}NR%2==0{print s;s=0}' testfileForSum.txt 
  • I have tried following but this works for only 1st row awk '{s+=$1}NR%2==0{print s;s=0}' testfileForSum.txt – RajaKashif Jun 3 '15 at 11:50
  • Are there always four elements in a row? – Janis Jun 3 '15 at 11:52
  • They are 7 elements but cannot it be generic for N elements – RajaKashif Jun 3 '15 at 11:53
  • Of course it can. - But that N is fixed for each line throughout the whole data file? – Janis Jun 3 '15 at 11:55
  • yes N is fixed for each line throughput the file – RajaKashif Jun 3 '15 at 11:55
2

One way with awk:

awk '
  NR%2 { split($0, a) ; next }
  { for (i=1; i<=NF; i++) printf " %d", a[i]+$i ; print "" }
'

Explanation: For lines with even number (NR%2) it will memorize the fields of the current line in an array a. And for the other (odd) lines there will be an iteration over the fields, and the sum of the respective memorized field a[i] and current field $i printed.

  • As I am knew to awk and this forum can you also explain the above solution as it will help me in future – RajaKashif Jun 3 '15 at 12:06
  • Doesnot seem to work on the following data. Seems to be an issue of the range. Works perfect otherwise. 845737163 5471453703 6945297424 44092072061 816281003 5704419737 6248800314 42808172792 – RajaKashif Jun 8 '15 at 4:16
  • @RajaKashif; Might be a integer range issue with your awk on your platform. - Should work with GNU awk. - What version of awk do you use and on which platform? – Janis Jun 8 '15 at 5:23
  • mawk 1.3.3 Nov 1996, Copyright (C) Michael D. Brennan compiled limits: max NF 32767 sprintf buffer 2040 – RajaKashif Jun 8 '15 at 13:13
  • I installed gawk and that solved the problem. Thanks @Janis – RajaKashif Jun 8 '15 at 13:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.