LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 02-13-2004, 05:54 PM   #1
elconde
Member
 
Registered: Sep 2001
Location: Cherry Hill, NJ
Distribution: Gentoo baby!
Posts: 67

Rep: Reputation: 15
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!
 
Old 02-13-2004, 10:42 PM   #2
elconde
Member
 
Registered: Sep 2001
Location: Cherry Hill, NJ
Distribution: Gentoo baby!
Posts: 67

Original Poster
Rep: Reputation: 15
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?
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
echo multiple lines of text twistedpair Linux - Software 9 08-08-2007 06:07 PM
Unique lines based on specific fields. carl.waldbieser Programming 6 08-21-2005 02:26 PM
ISDN multiple lines schimmelpilz Linux - Newbie 1 02-24-2004 05:39 PM
combining multiple dsl lines BaudRacer General 3 01-12-2004 09:15 AM
Handling multiple forms with same name hidden fields coolman0stress Programming 5 09-04-2003 01:34 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:51 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration