Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site trwatf.UUCP Path: utzoo!watmath!clyde!bonnie!akgua!mcnc!decvax!genrad!grkermi!panda!talcott!harvard!seismo!trwatf!root From: root@trwatf.UUCP Newsgroups: net.unix-wizards Subject: Adding up columns of numbers... Message-ID: <975@trwatf.UUCP> Date: Mon, 10-Jun-85 15:13:48 EDT Article-I.D.: trwatf.975 Posted: Mon Jun 10 15:13:48 1985 Date-Received: Sat, 15-Jun-85 06:57:50 EDT Reply-To: root@trwatf.UUCP (Lord Frith) Organization: TRW Advanced Technology Facility, Merrifield VA. Lines: 61 >> P.S. One strange omission (to my knowledge) from all the UNIX tools >> is a program, similar in command syntax (groan, but probably needed) >> to 'sort' which adds up columns of numbers: >> >> sumcol +4.6 foo >> >> Strange, must have been written hundreds of times. > > Awk is great for this. Something like: awk '{sum += $4}\\ > END {print sum}' > -mark Yes indeedy... here's a quick little script to get you started with multiple columns of numbers..... #! /bin/sh # Total multi-column numbers.... # TRW DSG EDS SISD SDL ATF STA-Jun-10 for f in $* do echo $f | awk '{ n = 80 - ( length($0) + 2 ) ; h = (n / 2) ; \ if ( n % 2 ) h = h-- ; \ for ( i = 1 ; i <= h ; i++ ) printf ">" ; \ printf " %s ",$0 for ( i = 1 ; i <= h ; i++ ) printf "<" ; \ printf "\n" \ }' cat $f | \ awk 'BEGIN { \ FS = " " ; for ( i = 0 ; i <= 25 ; i++ ) totals[i] = 0 \ } \ { \ if (length($0) > 0 ) { \ print $0 ; k = 1 ; \ for ( i = 2 ; i <= NF ; i++ ) \ if ( length($i) > 0 ) { \ if ( substr($i,1,1) == "$" ) \ $i = substr($i,2,length($i) - 1) k++ ; totals[k] += $i ; \ } \ } \ } \ END { printf "===================" ; \ for ( i = 2 ; i <= k ; i++ ) \ printf "================" ; \ printf "\n" ; \ printf "Total expenditures\t" ; \ for ( i = 2 ; i <= k ; i++ ) \ printf "\t\t$%d",totals[i] ; \ printf "\n" \ }' done -- UUCP: ...{decvax,ihnp4,allegra}!seismo!trwatf!root - Lord Frith ARPA: trwatf!root@SEISMO "Give a man a horse... and he thinks he's enormous"