Friday, October 7, 2022

[SOLVED] Calculate cumulative sum of fields within each line

Issue

Disclaimer: I'm a newbie.

I've been looking far and wide for an answer to my problem without success. If there are posts about this that I haven't found, please refer me to them!

I have been trying to use awk to calculate a cumulative sum for each field in each line of a rather large file of data. Any help would be much appreciated.

My file contains a couple of hundred thousand rows, where the rows vary in length (number of fields) and can be up to 100 fields long (i.e. up to 100 columns). The input looks like this (however actual numbers are way larger) and is tab separated:

12 9 2 1 7 1 4 5 1 7
19 1 1 1 1 1 1 2 5 1
45 1 5 1 8 1 2 1 4 1

I want the output to be in the format "new field 2 = field 1 + field 2" and "new field 3 = field 1 + field 2 + field 3" etc, i.e the output should look like this (printed in a new file):

12 21 23 24 31 32 36 41 42 49
19 20 21 22 23 24 25 27 32 33
45 46 51 52 60 61 63 64 68 69

I've been trying to use awk but can't for the life of me get it to work for every field (I don't want to type a command a hundred times).

Obviously I'm new to all this, and any solution that works will make me happy. Doesn't have to be awk. Thanks in advance for any help!


Solution

Following awk may help you here.

awk '{for(i=2;i<=NF;i++){$i=$i+$(i-1)}} 1'  Input_file

Explanation:

awk '{
for(i=2;i<=NF;i++){ ##Starting a for loop from value of 2 to till value of NF.
  $i=$i+$(i-1)}}    ##Adding value of current field with previous field here and assigning to itself.
1                   ##Mentioning 1 to print the current line with edited field values.
'  Input_file       ##Mentioning Input_file name here.


Answered By - RavinderSingh13
Answer Checked By - Candace Johnson (WPSolving Volunteer)