home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.unix.questions
- Path: sparky!uunet!ferkel.ucsb.edu!taco!gatech!paladin.american.edu!howland.reston.ans.net!spool.mu.edu!sgiblab!rtech!amdahl!amdcad!amdint.amd.com!diablo!monson
- From: monson@diablo.amd.com (Steve Monson)
- Subject: Re: How to add a list of numbers?
- Message-ID: <C1GqHs.t1@amd.com>
- Sender: usenet@amd.com
- Organization: Advanced Micro Devices, Inc., Austin, TX
- References: <1993Jan24.120619.5072@mark-one.inet-uk.co.uk> <1993Jan25.171527.9094@netcom.com>
- Date: Tue, 26 Jan 1993 13:22:39 GMT
- Lines: 47
-
- >In article <1993Jan24.120619.5072@mark-one.inet-uk.co.uk> mark@mark-one.inet-uk.co.uk (Mark Powell) writes:
- >What is the best (least CPU time) to addup a list of ASCII numbers?
- >eg you've just used cut to extract a list of file sizes from a ls -l
- >listing and now want to add all the numbers together. Is there some
- >utility that will do this?
- >All I can see is to write a for loop to add each number in turn to a
- >total, using expr.
-
- Well, using our ls -l, I get something like this:
-
- -rwx------ 1 monson 9320 Aug 7 08:36 timesheet
- -rwx------ 1 monson 349 Mar 24 1992 triplets
- -rwx------ 1 monson 1258 Dec 17 1991 ts
- -rwx------ 1 monson 473 Jun 17 1992 tu
- -rwx------ 2 monson 263 Sep 16 1991 unrot
- -rwx------ 1 monson 47 Apr 9 1991 unshar
- -rwx------ 1 monson 647 Jan 27 1992 uum
- -rwx------ 1 monson 1227 Oct 2 11:05 uumail
- -rw------- 1 monson 530 Apr 10 1992 uumail.sh
- -rwx------ 1 monson 1006 Oct 30 1990 uumdecode
- -rwx------ 1 monson 344 May 23 1991 wordcards
- -rwx------ 1 monson 1045 Sep 23 12:21 xcursors
-
- So I want to add up all the items in the 4th column. You can use "cut" to
- get the column entries, but multiple delimiters have to be compacted. So, the
- following command line runs ls, shrinks the white space to single blanks,
- extracts the 4th column, and changes all the blanks to "+" signs, and
- feeds the expression into bc, which prints the answer:
-
- echo `ls -l | sed 's/ */ /g' | cut -d\ -f4` | sed 's/ /+/g' | bc
-
- I suppose you could also use expr, but then you have to insert spaces
- around the plus signs, and make it all a single expression as arguments
- on the expr command line:
-
- expr `echo \`ls -l | sed 's/ */ /g' | cut -d\ -f4\` | sed 's/ / + /g'`
-
- but that starts to get messy, with the nested `` strings. Still, it avoids
- loops. Now, as to whether it's the "fastest," I have no idea. It does do a
- bunch of forks etc. to crank everything up. I suppose perl would be better;
- it often is.
-
- Steve
- -- monson@diablo.amd.com -- (512) 462-4013
- __ | signature designed by | If God were a liberal, we'd have the
- (_ | (and ripped off from) | Ten Suggestions.
- __)teve | Stephen Wayne Miller | James P. Hogan, _The Entoverse_
-