-1

I want to read a random txt which contains some random integers in this form:

2:10

4:4

10:15

22:5

Then i want to find the sum of each column . Firstly , i thought of spliting each line like if every line is a string:

columnA="$(cut -d':' -f1 <<<$line)"
columnB="$(cut -d':' -f2 <<<$line)"

columnAcontains the elements of the first column and columnB the elements of the second one . Then i created a variable sumA=0 and i tried to take the sum of each column like that:

sumA=$((columnA+sumA))

I am getting the result i want but with this message as well

")syntax error: operand expected (error token is "

Same for the second column :

sumB=$((columnB+sumB))

The time i am getting this error and i dont get the result i want: ")syntax error: invalid arithmetic operator (error token is "

This is the code in general :

sumA=0
sumB=0

while IFS= read -r line
do

columnA="$(cut -d':' -f1 <<<$line)"
sumA=$((columnA+sumA))

columnB="$(cut -d':' -f2 <<<$line)"
sumB=$((columnB+sumB))

done < "random.txt"

echo $sumA
echo $sumB

Any thoughts?

Abelisto
  • 14,826
  • 2
  • 33
  • 41

2 Answers2

2

It could be simplified just to

awk -F: '{sumA+=$1; sumB+=$2} END {printf "%s\n%s\n", sumA, sumB}' random.txt

From the manual:

$ man awk

...
-F fs
--field-separator fs
    Use fs for the input field separator (the value of the FS predefined variable).
...
Abelisto
  • 14,826
  • 2
  • 33
  • 41
0

instead of using "cut" use built in bash references: "${variable}"

ColumnA=0
ColumnB=0
while read l
do
ColumnA=$((${l//:*}+$ColumnA))
ColumnB=$((${l//*:}+$ColumnB))
done < random.txt
echo $ColumnA $ColumnB
PixelBlurb
  • 58
  • 6