Saturday, 15 June 2013

linux - how to multiply two tables in BASH -



linux - how to multiply two tables in BASH -

i have 2 info files this:

file1:

a1 a2 a3 ... b1 b2 b3 ... bn . . .

file1:

a1 a2 a3 ... b1 b2 b3 ... bn . . .

i want multiply 2 tables, i.e.,

a1*a1 a2*a2 a3*a3 ... an*an b1*b1 b2*b2 b3*b3 ... bn*bn . . .

can awk or else in bash? lot!

here's 1 way using gnu awk, assuming have same number of fields , rows in each file. run like:

awk -f script.awk file1 file2

contents of script.awk:

fnr==nr { (i=1;i<=nf;i++) { a[nr][i]=$i } next } { (j=1;j<=nf;j++) { $j = $j * a[fnr][j] } }1

alternatively, here's 1 liner:

awk 'fnr==nr { for(i=1;i<=nf;i++) a[nr][i]=$i; next } { for(j=1;j<=nf;j++) $j = $j * a[fnr][j] }1' file1 file2

testing:

contents of file1:

1 2 3 2 4 6

contents of file2:

3 4 5 6 7 8

results:

3 8 15 12 28 48

edit:

if, , mean if, there fields 1 file has other doesn't, change:

$j = $j * a[fnr][j]

to:

$j = (a[fnr][j] ? $j * a[fnr][j] : $j)

this print existing value , not zero. hth.

linux bash shell awk

No comments:

Post a Comment