views:

691

answers:

2

I want to shift away from Excel to Awk. I need basic mathematical operations, such as addition and division, for arrays.

For example, arrays A and B are [1, 3, 2] and [2, 1, 2], respectively. How can I get an array [2, 3, 4] from the multiplication between A and B? What about the addition and division between A and B?

+2  A: 

I think awk is not done for this sort of numeric work. It's more for text processing. Arrays in awk are associative and sparsely occupied (may have "holes" between its indexes). You use strings to index them:

for(int j=0; j<length(A) && j<length(B); j++)
    C[j] = A[j] * B[j]

It's like a hash-map. So, in awk you can do

A[100] = 10;
A[1] = 2;

And have only 2 elements stored in that array (elements from 2 to 99 do not exist), indexed by strings that are created by converting the numbers 100 and 1. The GNU Awk manual has a nice section about arrays in awk here.

Johannes Schaub - litb
+2  A: 

In awk "arrays" are associative. That is they are hashes indexed not by a continous string of numbers but by arbitrary input values. So you can do things like

for (i=0; i<3; i++){
   c[i] = a[i] * b[i];
};

if you know that the numerically indexed elements exist, or you can do things like:

d["sam"] = a[3] + b["dog"];

But array processing really isn't awk's strength, and I would advise taking a careful look at what is involved before committing wholesale to this course.

You might be better off with python or another fairly modern rapid development language.

BTW-- I wrote my first non-trivial bit of code in python last week, and I am totally hooked. After occasional exposure to tcl and perl, I was really wishy-washy on the value of these kinds of tools. I think python will make a believer out of me.

dmckee