Search code examples
bashfor-loopdivision

Dividing elements in two arrays with Bash


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

Solution

  • First, you have to use parens to declare your arrays.

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

    An alternate syntax -

    $: for i in ${!x[@]}; do echo "${x[i]} ${y[i]}"; done | awk '{print $1/$2}'
    108401
    121583
    192221
    122567
    147713
    130300
    127644
    113598
    122414
    118503
    

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

    You could also load your arrays into files of their own and just let awk handle all of it...

    $: cat x
    43035000
    51065000
    67085000
    36770000
    57165000
    54335000
    46590000
    64410000
    39295000
    37210000
    41800000
    
    $: cat y
    397
    420
    349
    300
    387
    417
    365
    567
    321
    314
    341
    
    $: awk 'NR==FNR{ dividend[FNR]=$1 } NR>FNR{ print dividend[FNR]/$1 }' x y
    108401
    121583
    192221
    122567
    147713
    130300
    127644
    113598
    122414
    118503
    122581