Joining multiple lines and summing fields
Say I have a file like this with lines consiting of usernames and homework scores. Some people didn't do all the homeworks, so there are less lines with their username.
% cat file
aalex 10
aalex 7
aalex 8
barga 10
barga 10
cally 8
deniseh 2
deniseh 3
deniseh 10
deniseh 10
Now how can I get a file like this which tallys the scores, and has one username per line.
% cat newfile
aalex 25
barga 20
cally 8
deniseh 25
I tried using an if then statement with awk, but I can't get it to work:
BEGIN { name = $1; score=0 }
{ newname=$1 }
if ( newname==name ) {
score += $2
} else {
printf "%s %d\n",name,score; name = $1; score=$2
}
which gives me
awk: syntax error near line 4
awk: bailing out near line 4
Help please!
|