LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Joining multiple lines and summing fields (https://www.linuxquestions.org/questions/programming-9/joining-multiple-lines-and-summing-fields-145804/)

elconde 02-13-2004 05:54 PM

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!

elconde 02-13-2004 10:42 PM

That's a really great question! Try this

#!/bin/bash

for student in `cat studentlist`
do
echo -n $student,
cat grade_file | awk "
/$student/ { score+=\$2 }
END {printf \"%d\",score }
" -
echo
done

I hope it works! You should post more interesting questions like this on the board. Can I have your number?


All times are GMT -5. The time now is 01:09 PM.