Previous Column Value (addition)

Good day,

First off, I would just like to say that I've been helped by a lot of the posts here in my own scripting work in the past few months. I've been a long time roamer, but first time poster. That being said, I'm stuck trying to figure out this issue (For computational research, not a homework problem).

The problem seems pretty simple: I have a file with two columns :

1234 2
1568 4
6895 6

What I'd like to do is take the value of the second column and add it to the previous value of the second column in the previous row, and print that as a third column. So, the output would look like this;

1234 2 2
1568 4 6
6895 5 11

The third column of the first row would be 2 (since a "previous" column does not exist), then the third column of the second row would be 4 (value of second column in second row) + 2 (value of the third column in previous row) = 6.

It would then go on to add 5 + 6 and put that in the third row of the third column, and so on and so forth down the list. The value of the first column does not matter for this problem, and the number of rows in the file would vary depending on what I'm studying.

I have attempted using awk (even dabbled some in arrays), but to no avail, and I've tried a simple bash shell script but I got hopeless stuck with for loops. I hope I made this as easy as possible to understand, and any help would be much appreciated!

Try this:

awk '{$3=$2+t;t+=$2}1' file

even shorter:

awk '{$3=t+=$2}1' file

Simple, elegant, and worked like a charm. Thank you so much for you help, it was a life saver!

Hello Franklin52,
Can you explain the purpose of "1" in your script?

awk '{$3=t+=$2}1' file 

Hum... nevermind ^^
I figured out:
awk '1' file == cat file

awk evaluates the 1 after the brace as true (not 0 or not empty) and the prints the current line by default, it's equivalent to {print}.