user3493435
user3493435

Reputation: 81

sum up value from textfile - bash

I am trying to sum up the values in a textfile

try.txt

firstNumber,1
secondNumber,2

I tried with this script

#!/bin/bash
while IFS, read -r -a array; do
     printf "%s %s\n" "${array[0]} ${array[1]}"
     for n in "${array[1]}"; do
        ((total += n))
        echo "total =" $total
     done
done < try.txt

and I landed up with this output

 firstNumber  1
 total = 1
 secondNumber  2
 total = 3

expected output

 firstNumber  1
 secondNumber  2
 total = 3

Thanks in advance

Upvotes: 0

Views: 65

Answers (2)

Samuel O&#39;Malley
Samuel O&#39;Malley

Reputation: 3541

Why not move your echo outside of your main loop?

#!/bin/bash
while IFS, read -r -a array; do
     printf "%s %s\n" "${array[0]} ${array[1]}"
     for n in "${array[1]}"; do
        ((total += n))
     done
done < try.txt
echo "total =" $total

Upvotes: 3

jkshah
jkshah

Reputation: 11703

Try using awk. It's best suited for well formatted tabular data manipulation.

awk -F, '{total+=$2; print $1,$2} END {print "total = "total}' try.txt

Output:

firstNumber 1
secondNumber 2
total = 3

Upvotes: 4

Related Questions