4
awk '{ for (i = 1; i <= NF; i++) sum[i]+=$i} END{for (i in sum) print sum[i]}' file1 > file2

This helps sum all record-wise but a similar scheme wouldn't help do a column-wise sum (maybe). How to generalize column-wise addition to n columns?

cat file1
23 46 45
45 57 58
56 78 74

cat file2
114
160
208
  • @user1271772 Committed to Materials Modeling SE. Thanks for the suggestion. It received 100 % commitment. – Hitanshu Sachania Apr 17 at 13:22
6

You want to compute the sum of the fields for each record, so it's just:

awk '{sum = 0; for (i = 1; i <= NF; i++) sum += $i; print sum}' < file1 > file2

The curly braces begin an action statement that is executed on every line of the input; there is no preceding condition that would limit its execution to lines that satisfy such a condition.

On each line:

  1. Initialize a sum variable to zero.
  2. Loop through the fields, starting at field #1 and ending at the last field (the special variable NF), and increment sum by the value of that field ($i).
  3. Print the value of the sum variable.
| improve this answer | |
  • 2
    I tried this but it doesn't complete. The command keeps running with no change on the terminal. – Hitanshu Sachania Feb 19 '19 at 18:10
  • 1
    @HitanshuSachania, you need to feed input to it, like by adding < file1 if that input is in the file1 file. – Stéphane Chazelas Feb 19 '19 at 18:11
  • 1
    Thank you, it worked. But I don't understand it, can you please explain it to me. – Hitanshu Sachania Feb 19 '19 at 18:18
  • 2
    @HitanshuSachania if you don't understand that, then how were you able to write the version from your answer, which is more complicated? (Notice however that the (for i in sum) is not guaranteed to iterate though the keys in any specific order (and it the real nawk the order for the 1..100 keys will be something like 59,22,2,23,3,...,21,1). – mosvy Feb 19 '19 at 18:51
  • 2
    @HitanshuSachania because awk arrays are usually implemented using a hash table and each implementation may use its own hash function, and may iterate through the keys in the order in which they're stored in the table + linked lists structure. Even with mawk (the default awk in debian) the following will print 21 first: awk 'BEGIN{a[1]=a[21]=1;for(i in a) print i}' – mosvy Feb 21 '19 at 1:10
1

This will be a little slower than awk, but it's very concise:

perl -MList::Util=sum0 -lane 'print sum0(@F)' file1

It uses the sum0 function of the core List::Util module.

| improve this answer | |
  • 1
    perl -lane 'my $s; $s += $_ for @F; print $s' < file1 – Rakesh Sharma Feb 20 '19 at 0:57

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.