multidimensional arrays in awk

ぃ、小莉子 提交于 2019-11-30 21:30:54

If you are using the simulated multi-dimensional arrays, your loop would need to be like this:

  END { 
    for (ij in a) {
      split(ij,indices,SUBSEP);
      i=indices[1];
      j=indices[2];
      print i,j,a[ij]
    }
  }

The (i,j) in a syntax only works for testing whether a particular index is in the array. It doesn't work for for-loops, despite the for-loop allowing a similar syntax.

For the true multi-dimensional arrays (arrays of arrays), you can write it like this:

BEGIN { FS=OFS="\t" }

{ a[$2+FS+$7][$3]+=$6 }

END { 
  for (i in a) {
    for (j in a[i]) { 
      print i,j,a[i][j]
    }
  }
}

However, arrays of arrays was only added in gawk 4.0, so your version of gawk may not support it.

Another note: on this line:

a[$2+FS+$7,$3]+=$6

It seems like you are trying to concatenate $2, FS, and $7, but "+" is for numerical addition, not concatenation. You would need to write it like this:

a[$2 FS $7,$3] += $6
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!