1. 程式人生 > >awk 數組

awk 數組

http world `` rip bracket hat stat part nat

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 數組是通過一個表達式進行索引,而這個表達式放在一對方括號中。如果該表達式是一個表達式列表(expr,expr ...),那麽這個數組的每一個索引是 每一個expr通過SUBSEP連接起來的整個expression.因為awk只支持一維數組,那麽如果數組索引是一個表達式,那麽就是一維數組;如果數組索引是 表達式列表,那麽就可以模擬多維數組。通常C語言中數組的索引是數字,所以從C的角度去考慮就會不好理解。但是如果從 key-value 數組的形式去考慮,例如 php,就很好理解awk的數組了。 示例: 一維數組: frank@ubuntu:~/test/shell$ awk ‘BEGIN{for (i=1;i<=2;i++) {array[i]=i*10};for (x in array) {print x,array[x]}}‘ 技術分享圖片

二維數組:

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]}}‘

技術分享圖片

如果自己設置SUBSEP變量,那麽可以看到索引表達式是由 SUBSEP 連接的。

技術分享圖片


awk 數組