从XYZ使用awk到矩阵 [英] from xyz to matrix with awk

查看:109
本文介绍了从XYZ使用awk到矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我设法与周围的工作来解决,所以我在这里希望与您更优雅的解决方案来学习问题; - )

I have a problem that I managed to solve with a work around so I am here hoping to learn from you more elegant solutions ;-)

我要解析程序的输出:它写入三列×一个文件yž这样

I have to parse the output of a program: it writes a file of three columns x y z like this

1 1 11  
1 2 12  
1 3 13  
1 4 14  
2 1 21  
2 2 22  
2 3 23  
2 4 24  
3 1 31  
3 2 32  
3 3 33  
3 4 34  
4 1 41  
4 2 42  
4 3 43  
4 4 44  

在这样的矩阵

11 12 13 14  
21 22 23 24  
31 32 33 34  
41 42 43 44  

我解决了,像这样

I solved with a two line bash script like this

dim_matrix=$(awk 'END{print sqrt(NR)}' file_xyz) #since I know that the matrix has to be squared and there are no blank lines in the file_xyz  
awk '{printf("%s%s",$3, !(NR%'${dim_matrix}'==0) ? OFS :ORS ) }' file_xyz  

能否请你建议我只使用awk执行相同的方法?

Can you please suggest me a way to perform the same only with awk?

推荐答案

awk并没有做实的多维数组,但你可以用一个正确构造字符串假的吧:

awk does not do real multidimensional arrays, but you can fake it with a properly constructed string:

awk '
  {mx[$1 "," $2] = $3}
  END {
    size=sqrt(NR)
    for (x=1; x<=size; x++) {
      for (y=1; y<=size; y++)
          printf("%s ",mx[x "," y])
      print ""
    }
  }
' filename

您可以用一个AWK电话,厕所

You can accomplish your example with a single awk call and a call to wc

awk -v "nlines=$(wc -l < filename)" '
  BEGIN {size = sqrt(nlines)}
  {printf("%s%s", $3, (NR % size == 0 ? ORS : OFS))
}' filename

这篇关于从XYZ使用awk到矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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