多维数组的 awk 数组迭代 [英] Awk array iteration for multi-dimensional arrays
问题描述
Awk 为数组处理提供关联索引.可以迭代一维数组的元素:
Awk offers associative indexing for array processing. Elements of 1 dimensional array can be iterated:
例如
for(index in arr1)
print "arr1[" index "]=" arr1[index]
但是这种二维数组是怎么做的呢?下面给出的某种语法是否有效?
But how this kind done for a two dimensional array? Does kind of syntax,given below work?
for(index1 in arr2)
for(index2 in arr2)
arr2[index1,index2]
推荐答案
AWK 通过将索引与保存在 SUBSEP 变量 (0x1c) 中的字符连接起来来伪造多维数组.您可以像这样使用 split
遍历二维数组(基于 info gawk
文件中的示例):
AWK fakes multidimensional arrays by concatenating the indices with the character held in the SUBSEP variable (0x1c). You can iterate through a two-dimensional array using split
like this (based on an example in the info gawk
file):
awk 'BEGIN { OFS=","; array[1,2]=3; array[2,3]=5; array[3,4]=8;
for (comb in array) {split(comb,sep,SUBSEP);
print sep[1], sep[2], array[sep[1],sep[2]]}}'
输出:
2,3,5
3,4,8
1,2,3
但是,您可以使用嵌套的 for 循环遍历数字索引数组:
You can, however, iterate over a numerically indexed array using nested for loops:
for (i = 1; i <= width; i++)
for (j = 1; j < = height; j++)
print array[i, j]
另一个值得注意的来自 GAWK 手册一个>:
Another noteworthy bit of information from the GAWK manual:
要测试特定索引序列是否存在于多维数组中,请使用与用于单维数组相同的运算符 (in).将整个索引序列写在括号中,用逗号分隔,作为左操作数:
To test whether a particular index sequence exists in a multidimensional array, use the same operator (in) that is used for single dimensional arrays. Write the whole sequence of indices in parentheses, separated by commas, as the left operand:
(subscript1, subscript2, ...) in array
Gawk 4 添加了数组数组.来自该链接:
Gawk 4 adds arrays of arrays. From that link:
for (i in array) {
if (isarray(array[i])) {
for (j in array[i]) {
print array[i][j]
}
}
else
print array[i]
}
另见遍历数组数组有关以下函数的信息,该函数遍历任意维度的数组数组,包括锯齿状数组:
Also see Traversing Arrays of Arrays for information about the following function which walks an arbitrarily dimensioned array of arrays, including jagged ones:
function walk_array(arr, name, i)
{
for (i in arr) {
if (isarray(arr[i]))
walk_array(arr[i], (name "[" i "]"))
else
printf("%s[%s] = %s
", name, i, arr[i])
}
}
这篇关于多维数组的 awk 数组迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!