Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 22 May 2000 12:54:31 +0100
From:      Ben Smithurst <ben@scientia.demon.co.uk>
To:        Dan Larsson <dl@tyfon.net>
Cc:        mj@isy.liu.se, questions@FreeBSD.ORG
Subject:   Re: calculate sum in sh
Message-ID:  <20000522125431.L15686@strontium.scientia.demon.co.uk>
In-Reply-To: <NEBBJANJCNNAKCPFKHHFAEHDCEAA.dl@tyfon.net>
References:  <XFMail.000522124146.mj@isy.liu.se> <NEBBJANJCNNAKCPFKHHFAEHDCEAA.dl@tyfon.net>

next in thread | previous in thread | raw e-mail | index | archive | help
Dan Larsson wrote:

> | Not pure shelling, but you can try this with awk
> | 
> | File 'crap.txt' is :
> | 
> | 1
> | 2
> | 3
> | 20
> | 
> | then 
> | 
> | lagrange> awk '{sum += $0} END{print "Grand total is "sum}' crap.txt
> | Grand total is 26
> 
> Perfect! Thanks! 

Or, in sh, without cheating, :-)

sum=0
while read n; do
	sum=$(($sum + $n))
done < crap.txt
echo "Grand total is $sum"

I'm not sure how portable $(( )) is, but it works at least in Linux
sh and FreeBSD sh, which is all I have access to.  If you want more
portability, the awk route is probably better.

-- 
Ben Smithurst / ben@scientia.demon.co.uk / PGP: 0x99392F7D


To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20000522125431.L15686>