From owner-freebsd-questions Mon May 22 5:24:37 2000 Delivered-To: freebsd-questions@freebsd.org Received: from scientia.demon.co.uk (scientia.demon.co.uk [212.228.14.13]) by hub.freebsd.org (Postfix) with ESMTP id E1C6437BBD2 for ; Mon, 22 May 2000 05:24:32 -0700 (PDT) (envelope-from ben@scientia.demon.co.uk) Received: from strontium.scientia.demon.co.uk ([192.168.91.36] ident=exim) by scientia.demon.co.uk with esmtp (Exim 3.12 #1) id 12tqn3-000Fjk-00; Mon, 22 May 2000 12:54:33 +0100 Received: (from ben) by strontium.scientia.demon.co.uk (Exim 3.12 #7) id 12tqn2-000DI8-00; Mon, 22 May 2000 12:54:32 +0100 Date: Mon, 22 May 2000 12:54:31 +0100 From: Ben Smithurst To: Dan Larsson Cc: mj@isy.liu.se, questions@FreeBSD.ORG Subject: Re: calculate sum in sh Message-ID: <20000522125431.L15686@strontium.scientia.demon.co.uk> References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Mailer: Mutt 1.0i In-Reply-To: Sender: owner-freebsd-questions@FreeBSD.ORG Precedence: bulk X-Loop: FreeBSD.ORG 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