[comp.unix.questions] What's wrong with this Bourne shell script?

aab@silma.com (Andy Burgess) (08/04/90)

On SunOS 4.03c this script:

----------------------- cut here --------------
:
total=0
ls -ld * | while read line
do
  set - `echo $line`
  total=`expr $total + $4`
  echo "Subtotal $total"
done
echo "Total $total"
----------------------- cut here --------------

The subtotal prints increasing numbers as you would expect.
At the end total prints as 0!
What gives?

While you're at it, is there a better way to get the total bytes
of the files in a directory?

Thanks

Andy Burgess

guy@auspex.auspex.com (Guy Harris) (08/05/90)

>The subtotal prints increasing numbers as you would expect.
>At the end total prints as 0!
>What gives?

You've been zapped by Mr. Subshell.

The Bourne shell runs some shell constructs in a sub-shell; apparently,
the construct you gave is one of them.  This means that the "total=`expr
$total + $4` gets run in the same shell each time through the loop, so
the subtotal increases; however, that shell is a subshell of the one
that echoes "Total $total", and variable settings done inside subshells
do not affect the settings of variables in the parent shell.  (To do so,
the subshell would have to inform the parent shell about them.)

This may change when shells become compliant with POSIX 1003.2, which
will presumably happen sometime after POSIX 1003.2 leaves the draft
stage and is approved; 1003.2 may put stricter controls on when a shell
may do something inside a subshell.  I don't have recent drafts handy;
Maarten?

>While you're at it, is there a better way to get the total bytes
>of the files in a directory?

Will "du -s" do?  It searches subdirectories of the given directory,
which your script doesn't; I suspect that's actually a bug in your
script, so "du -s" will do a better job.  ("du -s" also tries to avoid
counting files with multiple hard links to them more than once.)

ecl@cbnewsj.att.com (Evelyn C. Leeper) (08/05/90)

In article <1990Aug3.193231.3166@silma.com> aab@silma.UUCP (Andy Burgess) writes:
> ----------------------- cut here --------------
> total=0
> ls -ld * | while read line
> do
>   set - `echo $line`
>   total=`expr $total + $4`
>   echo "Subtotal $total"
> done
> echo "Total $total"
> ----------------------- cut here --------------
> At the end total prints as 0!
> What gives?

You cannot export shell variables from a child to a parent.  The while loop
spawns a subshell and "total" is know only to the subshell.  [Note: can
someone arrange to have this put in the "commonly asked questions" posting?]

Evelyn C. Leeper  |  +1 908-957-2070  |  att!mtgzy!ecl or  ecl@mtgzy.att.com
--
The only thing necessary for the triumph of evil is for good men to do nothing. 
                                                            -Edmund Burke

ask@cbnews.att.com (Arthur S. Kamlet) (08/06/90)

In article <1990Aug3.193231.3166@silma.com> aab@silma.UUCP (Andy Burgess) writes:
>While you're at it, is there a better way to get the total bytes
>of the files in a directory?

Well, wc .* *   will do a fairly good job (remember to surtract out
the . and .. figures.   If you want to find the nested files too,
combine with find.

But are you really interested in finding the number of bytes?
Perhaps for your need the number of blocks in the directory,
including nested directories in the same filesystem, can be found
more quickly by reading the superblock with a du -s dir_name

(On my Unix V system, if I don't have read permission, du will
silently not give me those sizes.)
-- 
Art Kamlet  a_s_kamlet@att.com  AT&T Bell Laboratories, Columbus

george@hls0.hls.oz (George Turczynski) (08/06/90)

In article <1990Aug3.193231.3166@silma.com>, aab@silma.com (Andy Burgess) writes:

> ...
> 
> While you're at it, is there a better way to get the total bytes
> of the files in a directory?

You could try something like this:

ls -ld * | awk '{ sum+= $4 } END { print sum }'

It does a similar thing to what your script is supposed to do.

Hope this is of some interest to someone...

George P. J. Turczynski.          | ACSnet: george@highland.oz
                                  | Phone: 61 48 683490
Computer Systems Engineer.        | Fax:   61 48 683474
                                  |----------------------
Highland Logic Pty. Ltd.          | I can't speak for the
Suite 1, 348-354 Argyle Street    | company, I can barely
Moss Vale. NSW. 2577 Australia    | speak for myself...

maart@cs.vu.nl (Maarten Litmaath) (08/06/90)

In article <3821@auspex.auspex.com>,
	guy@auspex.auspex.com (Guy Harris) writes:
)...
)The Bourne shell runs some shell constructs in a sub-shell; apparently,
)the construct you gave is one of them.  [...]

[The construct was ``command | while read line; do something; done''.]

)This may change when shells become compliant with POSIX 1003.2, which
)will presumably happen sometime after POSIX 1003.2 leaves the draft
)stage and is approved; 1003.2 may put stricter controls on when a shell
)may do something inside a subshell.  I don't have recent drafts handy;
)Maarten?

I haven't read Draft 10 yet, but I pleaded for the `while' loop from the
example to be run in the current shell instead of a subshell (if the user
wants a subshell he can always use parentheses).  The advantages are
obvious.

In any case, _redirected_ loops already must be run in the current shell,
notwithstanding the current practice in a lot of Bourne shell implementations
to create a subshell:

	var=before
	while read line
	do
		var=after
	done < file
	echo var=$var

This example will print `after' on POSIX 1003.2 conformant systems,
`before' on many current systems.
--
   "UNIX was never designed to keep people from doing stupid things, because
    that policy would also keep them from doing clever things."  (Doug Gwyn)

merlyn@iwarp.intel.com (Randal Schwartz) (08/07/90)

In article <1990Aug3.193231.3166@silma.com>, aab@silma (Andy Burgess) writes:
| While you're at it, is there a better way to get the total bytes
| of the files in a directory?

perl -e 'for(@ARGV){$x += (stat($_))[7];} print "$x bytes\n";' *

and soon (after the next patch):

perl -e 'for(@ARGV){$x += -s;} print "$x bytes\n";' *

Just another Perl hacker,
-- 
/=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\
| on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III      |
| merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn |
\=Cute Quote: "Welcome to Portland, Oregon, home of the California Raisins!"=/

scott@tab29.larc.nasa.gov (Scott Yelich (ODU) ) (08/07/90)

   In article <1990Aug3.193231.3166@silma.com> aab@silma.UUCP (Andy Burgess) writes:
   > ----------------------- cut here --------------
   > total=0
   > ls -ld * | while read line
   > do
   >   set - `echo $line`
   >   total=`expr $total + $4`
   >   echo "Subtotal $total"
   > done
   > echo "Total $total"
   > ----------------------- cut here --------------
   > At the end total prints as 0!
   > What gives?

As it has been said: It should.

However, I fiddle around with SH scripts... and this is how I would hack your script:

1)  I would not do it in perl-- I hate it when people ask about bourne shell and other 
   people reply with perl....  

#!/bin/sh

set - `ls -ld *`
while test "$6"
do
  shift 3
  EXPR="$1 + $EXPR"
  shift 5
done
echo "Total=`expr $EXPR 0 `"

Not that it really matters.... but there isn't a pipe in there nor so many calls to expr...
Of course, I didn't assign the variable total anywhere... unless you are going to use
it somewhere else, it isn't needed and it looked like you were just using it as a counter...

Scott
--
Signature follows. [Skip now]

 -----------------------------------------------------------------------------
 Scott D. Yelich                         scott@[xanth.]cs.odu.edu [128.82.8.1]
 After he pushed me off the cliff, he asked me, as I fell, ``Why'd you jump?''
 Administrator of:    Game-Design requests to <game-design-request@cs.odu.edu>
 ODU/UNIX/BSD/X/C/ROOT/XANTH/CS/VSVN/
 -----------------------------------------------------------------------------

guy@auspex.auspex.com (Guy Harris) (08/08/90)

>(On my Unix V system, if I don't have read permission, du will
>silently not give me those sizes.)

Try the "-r" option.

peter@ficc.ferranti.com (Peter da Silva) (08/08/90)

In article <1990Aug3.193231.3166@silma.com>, aab@silma.com (Andy Burgess) writes:
> total=0
> ls -ld * | while read line
	...
> echo "Total $total"

Unfortunately, that while loop is run by a subshell. Try this:

total=0
ls -ld * | {
	while read line
	...
	echo "Total $total"
}

Or (better) use AWK:

ls -ld * | awk '{
		total=total+$4;
		print "Subtotal " total
	}
	END { print "Total " total }'

(Someone will come up with a PERL version, 'tis certain)
-- 
Peter da Silva.   `-_-'
+1 713 274 5180.   'U`
<peter@ficc.ferranti.com>

lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (08/08/90)

In article <1990Aug3.193231.3166@silma.com>, aab@silma (Andy Burgess) writes:
| While you're at it, is there a better way to get the total bytes
| of the files in a directory?

In article <1990Aug6.172225.20319@iwarp.intel.com> merlyn@iwarp.intel.com (Randal Schwartz) writes:
: 
: perl -e 'for(@ARGV){$x += (stat($_))[7];} print "$x bytes\n";' *
: 
: and soon (after the next patch):
: 
: perl -e 'for(@ARGV){$x += -s;} print "$x bytes\n";' *

In article <SCOTT.90Aug7090149@tab29.larc.nasa.gov> scott@tab29.larc.nasa.gov (Scott Yelich     (ODU) ) writes:
: 
: However, I fiddle around with SH scripts... and this is how I would hack
: your script:
: 
: 1)  I would not do it in perl-- I hate it when people ask about bourne
:     shell and other people reply with perl....  

I refrain from labeling this as Irrational Prejudice, but it sure looks
like it.

In the first place, the command Randal gave is a *perfectly valid* Bourne
shell script.

In the second place, Andy asked if there was a better way.  Even if *you*
don't think it is a better way, you shouldn't try to keep other people
from helping.

I hate it when people think we're espousing Perl as the One True Way.
Perl is just another tool.  Use where appropriate.  Don't use where not.

Those are my Irrational Prejudices.

Larry Wall
lwall@jpl-devvax.jpl.nasa.gov

darcy@druid.uucp (D'Arcy J.M. Cain) (08/09/90)

In article <834@hls0.hls.oz> george@hls0.hls.oz (George Turczynski) writes:
>In article <1990Aug3.193231.3166@silma.com>, aab@silma.com (Andy Burgess) writes:
>> While you're at it, is there a better way to get the total bytes
>> of the files in a directory?
>You could try something like this:
>ls -ld * | awk '{ sum+= $4 } END { print sum }'

Here is a script I use to check directory usage:

------------------------ Start of script ----------------------------
#!
# Checks the space used by a directory
# Written by D'Arcy J.M. Cain

# default to current directory else from command line
if [ "$1" = "" ]
then
	directory=`pwd`
else
	directory=$1
	shift
fi

while true
do
	if [ "$directory" = "" ]
	then
		exit 0
	fi

	echo "$directory \c"
	ls -iRl $directory | awk '{ if (NF > 5) print $0 }' | sort | awk '{
		if ($1 != last_inode) size = size + $6
		last_inode = $1
		}
		END { print size }'

	if [ "$1" = "" ]
	then
		exit 0
	fi

	shift
	directory=$1
done
---------------------- End of script ----------------------

The difference is that subdirectories are included and links are only
counted once.  Also there is a little user friendly wrapping.  HTH.

-- 
D'Arcy J.M. Cain (darcy@druid)     |
D'Arcy Cain Consulting             |   MS-DOS:  The Andrew Dice Clay
West Hill, Ontario, Canada         |   of operating systems.
+ 416 281 6094                     |

scott@tab29.larc.nasa.gov (Scott Yelich (ODU) ) (08/09/90)

>: 1)  I would not do it in perl-- I hate it when people ask about bourne
>:     shell and other people reply with perl....  
>I refrain from labeling this as Irrational Prejudice, but it sure looks
>like it.

>In the second place, Andy asked if there was a better way.  Even if *you*
>don't think it is a better way, you shouldn't try to keep other people
>from helping.

I never said it wasn't a valid or even possibly better--
I simply said that when people ask for SH and other people reply with PERL,
something must have been lost in the translation...

If I want SH and I ask for SH and I get PERL... I wonder...

Perhaps Andy did ask for a better way-- others haven't.
Yet, what makes PERL a better way?  Especially for some of these one liners!

>I hate it when people think we're espousing Perl as the One True Way.
>Perl is just another tool.  Use where appropriate.  Don't use where not.

Perl is another tool.  I am attempting to decipher it.... but when someone
asks me for SH, I give them SH.

If they ask for a better way, I usually wait for you to respond with Perl.

> Those are my Irrational Prejudices.

Granted.
--
Signature follows. [Skip now]

 -----------------------------------------------------------------------------
 Scott D. Yelich                         scott@[xanth.]cs.odu.edu [128.82.8.1]
 After he pushed me off the cliff, he asked me, as I fell, ``Why'd you jump?''
 Administrator of:    Game-Design requests to <game-design-request@cs.odu.edu>
 ODU/UNIX/BSD/X/C/ROOT/XANTH/CS/VSVN/
 -----------------------------------------------------------------------------

peter@ficc.ferranti.com (Peter da Silva) (08/09/90)

In article <9053@jpl-devvax.JPL.NASA.GOV>, lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) writes:
> In the second place, Andy asked if there was a better way.  Even if *you*
> don't think it is a better way, you shouldn't try to keep other people
> from helping.

Canonical interjection about not depending on Perl for portable scripts.

Resigned comment about Perl not being buildable on all systems.

> I hate it when people think we're espousing Perl as the One True Way.
> Perl is just another tool.  Use where appropriate.  Don't use where not.

Request for example of problem for which shell is appropriate but Perl
is not, other than script portability considerations.
-- 
Peter da Silva.   `-_-'
+1 713 274 5180.   'U`
<peter@ficc.ferranti.com>

lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (08/10/90)

In article <SCOTT.90Aug9094016@tab29.larc.nasa.gov> scott@tab29.larc.nasa.gov (Scott Yelich     (ODU) ) writes:
: >I hate it when people think we're espousing Perl as the One True Way.
: >Perl is just another tool.  Use where appropriate.  Don't use where not.
: 
: Perl is another tool.  I am attempting to decipher it.... but when someone
: asks me for SH, I give them SH.

Well, yes, but in general you don't get SH.  You get SH plus some assortment
of more or less standard tools.  What some of you find irritating is that
some of us treat Perl as a more or less standard tool.  It's like kids--if
you expect them to be good, they generally are.  I expect Perl to become
a standard.  Therefore I treat it as such.  Therefore it's fair game to
suggest it as a solution to the problem the user is trying to solve.
I didn't see any complaint about the solutions involving awk, and that's
a different language than SH...

Admittedly, on some static scale of standardization, basic old awk scores
a little higher than Perl.  But I'm getting old and impatient, and just
don't have time to pussyfoot around.  So I'm assuming the tail can wag
the dog.

Here is Perl.  It's yours.  It's everybody's.  It's part of Unix.

Use it as appropriate.

Larry

jon@jonlab.UUCP (Jon H. LaBadie) (08/11/90)

In article <1990Aug6.172225.20319@iwarp.intel.com>, merlyn@iwarp.intel.com (Randal Schwartz) writes:
> In article <1990Aug3.193231.3166@silma.com>, aab@silma (Andy Burgess) writes:
> | While you're at it, is there a better way to get the total bytes
> | of the files in a directory?
> 
>    PERL SCRIPT DELETED

A script of mine called "addcol" was printed in UNIX World's monthly
column Wizard's Grabbag and would do the same thing without perl;

	ls -ld | addcol -4

However, have we forgotten our roots?  I'm surprised in this thread
that no one has mentioned:

	TOTAL=`cat * | wc -c`

Jon

-- 
Jon LaBadie
{att, princeton, bcr}!jonlab!jon
{att, attmail, bcr}!auxnj!jon

lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (08/12/90)

In article <850@jonlab.UUCP> jon@jonlab.UUCP (Jon H. LaBadie) writes:
: In article <1990Aug6.172225.20319@iwarp.intel.com>, merlyn@iwarp.intel.com (Randal Schwartz) writes:
: > In article <1990Aug3.193231.3166@silma.com>, aab@silma (Andy Burgess) writes:
: > | While you're at it, is there a better way to get the total bytes
: > | of the files in a directory?
: > 
: >    PERL SCRIPT DELETED
: 
: A script of mine called "addcol" was printed in UNIX World's monthly
: column Wizard's Grabbag and would do the same thing without perl;
: 
: 	ls -ld | addcol -4
: 
: However, have we forgotten our roots?  I'm surprised in this thread
: that no one has mentioned:
: 
: 	TOTAL=`cat * | wc -c`

Let us be explicit about the advantages and disadvantages of these
approaches.  Any naive approach using ls is gonna screw up in /dev,
and probably does the opposite of what you want on symbolic links.
The cat approach has to read all the bytes (try it on a swapfile), but
probably does what you want on symbolic links.  It may or may not do
what you want on files with holes in them.  It doesn't do what you want
with the last access times.  It CERTAINLY doesn't do what you want in /dev,
or in a directory containing a FIFO or a Unix domain socket.

The stat structure in C is quite straightforward by comparison.  Pity
there's such a big ecological niche between shell and C...

Larry

merlyn@iwarp.intel.com (Randal Schwartz) (08/12/90)

In article <850@jonlab.UUCP>, jon@jonlab (Jon H. LaBadie) writes:
| However, have we forgotten our roots?  I'm surprised in this thread
| that no one has mentioned:
| 
| 	TOTAL=`cat * | wc -c`

Because it (a) skips files that start with dot, and (b) is *horribly*
inefficient.  Don't try this at home, kiddies!

Just another UNIX hacker (and look, I didn't mention Perl here, either),
-- 
/=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\
| on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III      |
| merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn |
\=Cute Quote: "Welcome to Portland, Oregon, home of the California Raisins!"=/

chip@chinacat.Unicom.COM (Chip Rosenthal) (08/13/90)

In article <9116@jpl-devvax.JPL.NASA.GOV>
	lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) writes:
>In article <850@jonlab.UUCP> jon@jonlab.UUCP (Jon H. LaBadie) writes:
>: 	ls -ld | addcol -4
>: [or]
>: 	TOTAL=`cat * | wc -c`
>[ls messes up on non-regular files; cat is inefficient]

If you snarfed the "stat" program I posted to alt.sources recently,
I'd suggest:

    echo 0`stat -s * | sed -e 's/.*:/+/'` | bc

or if you have Jon's addcol, even simpler:

    stat -s * | addcol -2

-- 
Chip Rosenthal                            |  You aren't some icon carved out
chip@chinacat.Unicom.COM                  |  of soap, sent down here to clean
Unicom Systems Development, 512-482-8260  |  up my reputation.  -John Hiatt

fpb@ittc.wec.com (Frank P. Bresz) (08/14/90)

In article <1474@chinacat.Unicom.COM> chip@chinacat.Unicom.COM (Chip Rosenthal) writes:

>If you snarfed the "stat" program I posted to alt.sources recently,
>I'd suggest:

>    echo 0`stat -s * | sed -e 's/.*:/+/'` | bc

>or if you have Jon's addcol, even simpler:

>    stat -s * | addcol -2

	Where is Jon's addcol.  I tried to write one a while back and kept
screwing it up.  I would like to see a working version.
--

					Frank P. Bresz }*{
					ITTC Network Administrator
+--------------------+
|fbresz@ittc.wec.com |  My opinions are my own, I'm not paid
|uunet!ittc!fbresz   |  enough to make an official statement  
|(412)733-6749       |  +-----------------------------------+
|Fax: (412)733-6444  |  |      THIS SPACE FOR SALE!!!       |
+--------------------+  +-----------------------------------+

merlyn@iwarp.intel.com (Randal Schwartz) (08/15/90)

In article <FPB.90Aug13191108@ittc.ittc.wec.com>, fpb@ittc (Frank P. Bresz) writes:
| >or if you have Jon's addcol, even simpler:
| 
| >    stat -s * | addcol -2
| 
| 	Where is Jon's addcol.  I tried to write one a while back and kept
| screwing it up.  I would like to see a working version.

for addcol -1, try:

	perl -ane '$s += $F[0]; print "$s\n" if eof;'

for addcol -2:

	perl -ane '$s += $F[1]; print "$s\n" if eof;'

Others may be derived by noticing the pattern. :-)

Just another Perl hacker,
-- 
/=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\
| on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III      |
| merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn |
\=Cute Quote: "Welcome to Portland, Oregon, home of the California Raisins!"=/

harrison@necssd.NEC.COM (Mark Harrison) (08/16/90)

In article <FPB.90Aug13191108@ittc.ittc.wec.com>,
   fpb@ittc.wec.com (Frank P. Bresz) writes:
> 	Where is Jon's addcol.  I tried to write one a while back and kept
> screwing it up.  I would like to see a working version.

Here is a simple one in awk.  Replace $4 with your column number.

		awk '{ tot += $4} END{print tot}'
			      ^^
If you put this into a shell script called addcol, you can say

		awk '{ tot += $'$1'} END{print tot}'

and invoke it by
		addcol 4

Example:  How many bytes in my files?

		ls -l c* | awk '{ tot += $4} END{print tot}'
		ls -l c* | addcol 4

Hope this helps!
-- 
Mark Harrison             harrison@necssd.NEC.COM
(214)518-5050             {necntc, cs.utexas.edu}!necssd!harrison
standard disclaimers apply...

fpb@ittc.wec.com (Frank P. Bresz) (08/16/90)

In article <1990Aug14.171056.17982@iwarp.intel.com> merlyn@iwarp.intel.com (Randal Schwartz) writes:

>In article <FPB.90Aug13191108@ittc.ittc.wec.com>, fpb@ittc (Frank P. Bresz) writes:
>| >or if you have Jon's addcol, even simpler:
>| 
>| >    stat -s * | addcol -2
>| 
>| 	Where is Jon's addcol.  I tried to write one a while back and kept
>| screwing it up.  I would like to see a working version.

>for addcol -1, try:
>	perl -ane '$s += $F[0]; print "$s\n" if eof;'
>for addcol -2:
>	perl -ane '$s += $F[1]; print "$s\n" if eof;'

>Others may be derived by noticing the pattern. :-)
>Just another Perl hacker,

	That would be fine if I had or wanted pearl.  I was under the
impression that Jon's addcol was an awk script (I think that's where the
original thread came from anway) in which the -# was the column you wanted
to add and it would magically add up the numbers in column 1 or 7 or
whatever column you wanted under argumentalized control instead of having
separate scripts for each possible set of columns you want to add.
--
+--------------------+
|fbresz@ittc.wec.com |  My opinions are my own, I'm not paid
|uunet!ittc!fbresz   |  enough to make an official statement  
|(412)733-6749       |  +-----------------------------------+
|Fax: (412)733-6444  |  |      THIS SPACE FOR SALE!!!       |
+--------------------+  +-----------------------------------+

merlyn@iwarp.intel.com (Randal Schwartz) (08/16/90)

In article <FPB.90Aug16005419@ittc.ittc.wec.com>, fpb@ittc (Frank P. Bresz) writes:
| 	That would be fine if I had or wanted pearl.  I was under the
| impression that Jon's addcol was an awk script (I think that's where the
| original thread came from anway) in which the -# was the column you wanted
| to add and it would magically add up the numbers in column 1 or 7 or
| whatever column you wanted under argumentalized control instead of having
| separate scripts for each possible set of columns you want to add.

Well, the script in awk is almost as easy:

... | awk '{ $x += $3 }
END { print $x }' |

who needs anything else?  (But in Perl you can write it in one line. :-)

Just another Perl hacker, more-or-less,
-- 
/=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\
| on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III      |
| merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn |
\=Cute Quote: "Welcome to Portland, Oregon, home of the California Raisins!"=/

tchrist@convex.COM (Tom Christiansen) (08/16/90)

In article <FPB.90Aug16005419@ittc.ittc.wec.com> fbresz@ittc.wec.com writes:
[chiding of Randal deleted]
>	That would be fine if I had or wanted pearl.  I was under the
>impression that Jon's addcol was an awk script (I think that's where the
>original thread came from anway) in which the -# was the column you wanted
>to add and it would magically add up the numbers in column 1 or 7 or
>whatever column you wanted under argumentalized control instead of having
>separate scripts for each possible set of columns you want to add.

You mean perl, but anyway....

    usage: addcol field_number

as in 'ls -l | addcol 5'

    #!/bin/sh
    field=$1
    shift
    awk "{sum += \$$field;}END {print sum}" $*

If you want to bullet-prove it against bad args, you can 
do more checking

--tom
--
Tom Christiansen                       {uunet,uiucdcs,sun}!convex!tchrist 
Convex Computer Corporation                            tchrist@convex.COM
  "UNIX was never designed to keep people from doing stupid things,
   because that policy would also keep them from doing clever things." [gwyn]

fpb@ittc.wec.com (Frank P. Bresz) (08/17/90)

In article <416@necssd.NEC.COM> harrison@necssd.NEC.COM (Mark Harrison) writes:
>Here is a simple one in awk.  Replace $4 with your column number.
>		awk '{ tot += $4} END{print tot}'
>			      ^^
>If you put this into a shell script called addcol, you can say
>		awk '{ tot += $'$1'} END{print tot}'
>and invoke it by
>		addcol 4
>Example:  How many bytes in my files?
>		ls -l c* | awk '{ tot += $4} END{print tot}'
>		ls -l c* | addcol 4

>Hope this helps!

	It is EXACTLY what I was looking for.  Thank you very much for
weeding through and figuring out what I really wanted.!!
--
+--------------------+
|fbresz@ittc.wec.com |  My opinions are my own, I'm not paid
|uunet!ittc!fbresz   |  enough to make an official statement  
|(412)733-6749       |  +-----------------------------------+
|Fax: (412)733-6444  |  |      THIS SPACE FOR SALE!!!       |
+--------------------+  +-----------------------------------+