Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

bash - Shell script to sum columns associated with a name

I have a file with thousands of numbers on column 1 and each sequence of these numbers are associated with a single person. Would someone have any idea on how can I create a shell script to sum column 1 for that specific person, eg:

John is 10+20+30+50 = 110

Output of the script would be: John 110 and so on and so forth..

I have tried with while, for, etc but I can't associate the sum to the person :(

Example of the file:

10 John
20 John
30 John
50 John
10 Paul
10 Paul
20 Paul
20 Paul
20 Robert
30 Robert
30 Robert 
60 Robert 
80 Robert
40 Robert
40 Robert
40 Robert
15 Mike
30 Mike
question from:https://stackoverflow.com/questions/65938564/shell-script-to-sum-columns-associated-with-a-name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
awk '{ map[$2]+=$1 } END { for (i in map) { print i" "map[i] } }' file

Using awk, create an array with the name as the first index and a running total of the values for each name. At the end, print the names and totals.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...