user2369478
user2369478

Reputation: 63

how to sum double numbers in bash

I want to do a sum in bash, but numbers are with dot and not with comma (Ex: 1.2333)

I tried to do this script

#!/bin/bash 
somma=0 
n=0 
tempo=0
val=0
while read -r val1 val2 
do 
  somma=$((somma += val1))
  tempo=$(echo $tempo += $val2 | bc) 
  n=$((n +=+1)) 
done < "ret.txt" 
echo $tempo

but I got this error:

 (standard_in) 1: syntax error

Upvotes: 1

Views: 2161

Answers (2)

glenn jackman
glenn jackman

Reputation: 247092

awk '
    {sum1 += $1; sum2 += $2} 
    END {print "somma=" sum1; print "tempo=" sum2}
' filename

If you need those values in your bash script, eval the output of that awk command, or:

read somma tempo < <(
    awk '{sum1 += $1; sum2 += $2} END {print sum1, sum2}' filename
)

Upvotes: 3

Aleks-Daniel Jakimenko-A.
Aleks-Daniel Jakimenko-A.

Reputation: 10663

#!/bin/bash
somma=0
n=0
tempo=0
val=0
while read -r val1 val2; do
    ((somma += val1))
    tempo=$(bc <<< "$tempo + $val2")
    ((n++))
done < "ret.txt"
echo "$tempo"

Upvotes: 2

Related Questions