Shaedeycool
Shaedeycool

Reputation: 3

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

Upvotes: 0

Views: 98

Answers (3)

Paul Hodges
Paul Hodges

Reputation: 15408

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

Upvotes: 0

M. Nejat Aydin
M. Nejat Aydin

Reputation: 10133

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.

Upvotes: 2

Adri&#225;n B&#237;ro
Adri&#225;n B&#237;ro

Reputation: 39

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

Upvotes: 0

Related Questions