Awk array iteration for multi-dimensional arrays

后端 未结 5 1295
不思量自难忘°
不思量自难忘° 2020-12-25 13:25

Awk offers associative indexing for array processing. Elements of 1 dimensional array can be iterated:

e.g.

for(index in arr1)
  print \"arr1[\" inde         


        
5条回答
  •  萌比男神i
    2020-12-25 14:17

    No, the syntax

    for(index1 in arr2) for(index2 in arr2) {
        print arr2[index1][index2];
    }
    

    won't work. Awk doesn't truly support multi-dimensional arrays. What it does, if you do something like

    x[1,2] = 5;
    

    is to concatenate the two indexes (1 & 2) to make a string, separated by the value of the SUBSEP variable. If this is equal to "*", then you'd have the same effect as

    x["1*2"] = 5;
    

    The default value of SUBSEP is a non-printing character, corresponding to Ctrl+\. You can see this with the following script:

    BEGIN {
        x[1,2]=5;
        x[2,4]=7;
        for (ix in x) {
            print ix;
        }
    }
    

    Running this gives:

    % awk -f scriptfile | cat -v
    1^\2
    2^\4
    

    So, in answer to your question - how to iterate a multi-dimensional array - just use a single for(a in b) loop, but you may need some extra work to split up a into its x and y parts.

提交回复
热议问题