Home > front end >  Dividing elements in two arrays with Bash
Dividing elements in two arrays with Bash

Time:11-23

I have two arrays of:

x=43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000
y=397 420 349 300 387 417 365 567 321 314 341

I would like to divide the first number in x with the first number in y and the second number in x with the second number in y and so on...

I have tried:

for i in "${x[@]}"; do for j in "${y[@]}"; do awk "{print $i/$j}"; done; done

however it just lists the numbers in x and then the numbers in y:

43035000
51065000
67085000
36770000
57165000
54335000
46590000
64410000
39295000
37210000
41800000
397
420
349
300
387
417
365
567
321
314
341

CodePudding user response:

Assuming both arrays contain the same number of elements and all elements are numeric, you can use a C-style for loop in bash:

x=(43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000)
y=(397 420 349 300 387 417 365 567 321 314 341)
for ((i=0; i<${#x[@]};   i)); do echo "${x[i]} ${y[i]}"; done |
    awk '{print $1/$2}'

Or, if all you need is integer truncated division, you can use shell arithmetic (you don't need awk in this case):

for ((i=0; i<${#x[@]};   i)); do echo $((x[i] / y[i])); done

Note that this second solution won't work if numerator or denominator isn't integer or you want a floating-point result.

CodePudding user response:

You should pass variable to awk like this

$ x=(43035000 51065000 67085000 36770000 57165000 54335000 46590000 64410000 39295000 37210000 41800000)
$ y=(397 420 349 300 387 417 365 567 321 314 341)

$ for (( i=0; i<${#x[@]}; i   )); 
do 
    awk -v I=${x[$i]} -v J=${y[$i]} 'BEGIN{print I / J}';
done

CodePudding user response:

An alternate syntax -

$: declare -p x y
$: for i in ${!x[@]}; do echo "x($i)=${x[i]} y($i)=${y[i]} x/y=$(( ${x[i]} / ${y[i]} ))"; done
x(0)=43035000 y(0)=397 x/y=108400
x(1)=51065000 y(1)=420 x/y=121583
x(2)=67085000 y(2)=349 x/y=192220
x(3)=36770000 y(3)=300 x/y=122566
x(4)=57165000 y(4)=387 x/y=147713
x(5)=54335000 y(5)=417 x/y=130299
x(6)=46590000 y(6)=365 x/y=127643
x(7)=64410000 y(7)=567 x/y=113597
x(8)=39295000 y(8)=321 x/y=122414
x(9)=37210000 y(9)=314 x/y=118503
x(10)=41800000 y(10)=341 x/y=122580

For any array foo, ${!foo[@]} returns a list of the indexes/keys.
So long as x & y have the same number of keys, this should work fine, though it's only integer math.

  • Related