awk array

Arrays
        Arrays are subscripted with an expression between square brackets ([ and ]) .  
  If the expression is an expression list (expr, expr ...)  then the array subscript is a string consisting of  the concatenation of the (string) value of each expression, separated by the value of the SUBSEP variable.  
  This facility is used to simulate multiply dimensioned arrays.  
  For example:
              i = "A"; j = "B"; k = "C"
              x[i, j, k] = "hello, world\n"
       assigns the string "hello, world\n" to the element of the array x which is indexed by the string "A\034B\034C".  All arrays in AWK are associative , i.e. indexed by string values .
 
       The special operator in may be used to test if an array has an index consisting of a particular value:
              if (val in array)
                   print array[val]
       If the array has multiple subscripts, use (i, j) in array.
       The in construct may also be used in a for loop to iterate over all the elements of an array.
       An element may be deleted from an array using the delete statement.  The delete statement may also be used to delete the entire contents of an array, just by specifying the array name without a subscript.
 
       gawk supports true multidimensional arrays. It does not require that such arrays be ``rectangular'' as in C or C++.  For example:
              a[1] = 5
              a[2][1] = 6
              a[2][2] = 7
 
Arrays are indexed by an expression enclosed in square brackets. If the expression is a list of expressions (expr, expr ...), then each index of this array is the entire expression of each expr concatenated by SUBSEP. Because awk only supports one-dimensional arrays, then if the array index is An expression, then a one-dimensional array; if the array index is a list of expressions, then you can simulate a multidimensional array. Usually the index of an array in C language is a number, so it is not easy to understand from the perspective of C. But if you consider it from the form of key-value array, such as php, you can understand awk's array very well.
 
Example:
 
One-dimensional array:
frank@ubuntu:~/test/shell$ awk 'BEGIN{for (i=1;i<=2;i++) {array[i]=i*10};for (x in array) {print x,array[x]}}'

Two-dimensional array:

frank@ubuntu:~/test/shell$ awk 'BEGIN{ for (i=1;i<=2;i++) {for (j=1;j<=3;j++) {array[i,j]=i*j*10}};  for (x in array) {print x,array[x]}}'

If you set the SUBSEP variable yourself, you can see that the index expressions are connected by SUBSEP.

 

 


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324607816&siteId=291194637
awk