Awk array iteration for multi-dimensional arrays

后端 未结 5 1303
不思量自难忘°
不思量自难忘° 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条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-25 14:11

    awk(1) was originally designed -- in part -- to be teaching tool for the C language, and multi-dimensional arrays have been in both C and awk(1) pretty much forever. as such POSIX IEEE 1003.2 standardized them.

    To explore the syntax and semantics, if you create the following file called "test.awk":

    BEGIN {
      KEY["a"]="a";
      KEY["b"]="b";
      KEY["c"]="c";
      MULTI["a"]["test_a"]="date a";
      MULTI["b"]["test_b"]="dbte b";
      MULTI["c"]["test_c"]="dcte c";
    }
    END {
      for(k in KEY) {
        kk="test_" k ;
        print MULTI[k][kk]
      }
      for(q in MULTI) {
        print q
      }
      for(p in MULTI) {
        for( pp in MULTI[p] ) {
          print MULTI[p][pp]
        }
      }
    }
    

    and run it with this command:

    awk -f test.awk /dev/null
    

    you will get the following output:

    date a
    dbte b
    dcte c
    a
    b
    c
    date a
    dbte b
    dcte c
    

    at least on Linux Mint 18 Cinnamon 64-bit 4.4.0-21-generic #37-Ubuntu SMP

提交回复
热议问题