Reputation: 259
I have a file with 2 columns separated by space delimiter:
Location 5
AdministrativeRegion 2
Person 3
Athlete 4
FloweringPlant 8
Film 1
Actor 2
I want to have a cumulative total of numbers of second column in a third column like:
Location 5 5
AdministrativeRegion 2 7
Person 3 10
Athlete 4 14
FloweringPlant 8 22
Film 1 23
Actor 2 25
I know this can be achieved with awk
With something similar to: awk '{total += $0; $0 = total}1'
But I want the result in a new column.
Hope you can help me. Thanks in advance.
Upvotes: 1
Views: 109
Reputation: 36570
I would use GNU AWK
for this task following way, let file.txt
content be
Location 5
AdministrativeRegion 2
Person 3
Athlete 4
FloweringPlant 8
Film 1
Actor 2
then
{total+=$2;print $0,total}
output
Location 5 5
AdministrativeRegion 2 7
Person 3 10
Athlete 4 14
FloweringPlant 8 22
Film 1 23
Actor 2 25
Explanation: In each line increase (+=
) total
by value from 2nd column ($2
) then print
whole line as is ($0
) followed by current total
.
(tested in gawk 4.2.1)
Upvotes: 1