Reputation: 23
So I have a text file like this:
1.0 56
2.0 48
1.0 78
1.0 12
3.0 68
the 1.0, 2.0 are all user id and i have up till 43.0. so i wrote an awk script to process the file:
BEGIN {
total = 0
}
{
length = $2
}
{
if ($1 == "1.0") {
total += length
}
}
END {
printf("%.2f\n",total)
}
so basically it takes the sum of the lengths of user 1.0 and sums it all. I have to do that to the other users as well. What changes should i do in the script so that it processes the text file completely for user 1.0, 2.0, 3.0, etc and gives the totals for each user as output (without having to change the awk
file everytime i have to compute for a user)
Upvotes: 1
Views: 56
Reputation: 85800
You can do something like this in awk
awk '{unique[$1]+=$2}END{for (i in unique) print i,unique[i]}' input-file
The idea is the above creates a hash-map, with $1
being the unique entry in the array which has your values from 1.0
, 2.0
etc. We are adding the value of length which is $2
in the file. Since the array is indexed by $1
, the command updates the sum for every unique user in the file. The END
clause is executed after all the lines are processed which basically prints out the user id with the sum calculated.
Upvotes: 1