LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bash mathematics possible? (https://www.linuxquestions.org/questions/linux-newbie-8/bash-mathematics-possible-175992/)

stabu 04-29-2004 01:03 PM

bash mathematics possible?
 
Hi,
Can bash add numbers within a file if the file is simple?
Eg. I have a file with numbers. They're separated by new lines. That's all there is in it.
Can it add them up or perform some maths processing on them?

320mb 04-29-2004 01:43 PM

http://www.linuxquestions.org/questi...highlight=calc

sure, why not??

Matt Collier 04-29-2004 02:17 PM

always baffles me that people use bash for non system stuff when there's far better scripting languages available

#!/usr/bin/perl -w

use warnings;
use strict;

my $file = 'numbers';
my $total;

open NUMBERFILE, $file or die "cannot open file '$file': $!";
while (my $number = <NUMBERFILE>) {
$total += $number;
}
close NUMBERFILE

print "the total of $file is $total\n";

wapcaplet 04-29-2004 03:14 PM

Though, why use a complicated perl script when a one-line bash command will do?

If your input file is called numbers.txt, then something like this:

Code:

let sum=0; for num in `cat numbers.txt`; do let sum=sum+$num; done; echo $sum
There's probably a simpler way to do it, but this'll get the job done.

megaspaz 04-29-2004 03:39 PM

yes, bash can do math on numbers, provided that they're integers and not floating point numbers(ie. 0.0056, 1.5, etc....).

stabu 04-30-2004 04:45 AM

Thanks for answers.

I was reading up about "bc" and tried various ways to use it using xargs to pass arguments to it, but it wouldn't give. Needs more research. I guess.

I suppose I want to do this in bash because it's (or its brother and sister shells) available on old and minimal distros. Besides I wouldn't like to assume perl everywhere I go

Actually I am a perl fan, and any chance to brush up is welcome, so thanks for script Matt. Though: isn't "use warnings;" redundant after the -w shebang line?

Naturally I could also load the file into gnumeric and sum off from there but the fun is not only doing it, but finding the most efficent ways of doing it.

BTW all this come from grep -ch *, which counts the occurences of a word in all the files of a directory. I'm going to try out wapcaplet's sugg later on and check out bc a bit more, as it does handle floating point, and looks to be fairly powerful.


All times are GMT -5. The time now is 05:14 PM.