awk 数组
Posted suonikeyinsu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了awk 数组相关的知识,希望对你有一定的参考价值。
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 数组的主要内容,如果未能解决你的问题,请参考以下文章