awk的数组迭代多维数组 [英] Awk array iteration for multi-dimensional arrays

查看:203
本文介绍了awk的数组迭代多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

awk提供了阵列处理关联索引。一维数组的元素可以进行迭代:

例如

 的(指数ARR1)
  打印ARR1 [指数] =ARR1 [指数]

但是怎么样了二维数组做了什么?下面的工作并不给出一种语法,?

 为(索引1中ARR2)
对(在ARR2索引2)
   ARR2 [索引1,索引2]


解决方案

AWK通过连接与在SUBSEP变量(0x1C处)举办的字符指数假货多维数组。可以使用拆分通过二维数组迭代这样的(基于信息为例GAWK 文件)

 的awk'BEGIN {OFS =;数组[1,2] = 3;数组[2,3] = 5;数组[3,4] = 8;
  对于(数组梳){拆分(梳9月,SUBSEP);
    打印月[1],SEP [2],数组[SEP [1],SEP [2]}}'

输出:

  2,3,5
3,4,8
1,2,3

您可以,但是,使用嵌套的for循环遍历一个数字索引数组:

 为(i = 1; I< =宽度;我++)
    为(J = 1; J< =身高; J ++)
        打印数组[I,J]

从<一个信息另一个值得注意的位href=\"http://www.gnu.org/software/gawk/manual/html_node/Multi_002ddimensional.html#Multi_002ddimensional\">GAWK手动:


  

要测试多维数组中是否存在特定的索引序列,使用相同的操作符(在),它用于单维数组。写在括号指数,用逗号分隔的整个序列,作为左操作数:

 (subscript1,subscript2,...)的阵列


Awk offers associative indexing for array processing. Elements of 1 dimensional array can be iterated:

e.g.

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

Output:

2,3,5
3,4,8
1,2,3

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]

Another noteworthy bit of information from the GAWK manual:

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

这篇关于awk的数组迭代多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆