Convert column to matrix format using awk

前端 未结 4 2220
有刺的猬
有刺的猬 2021-02-15 16:36

I have a gridded data file in column format as:

ifile.txt
x     y     value
20.5  20.5  -4.1
21.5  20.5  -6.2
22.5  20.5   0.0
20.5  21.5   1.2
21.5  21.5   4.3
         


        
4条回答
  •  轮回少年
    2021-02-15 17:06

    awk solution:

    sort -n ifile.txt | awk 'BEGIN{header="\t"}NR>1{if((NR-1)%3==1){header=header sprintf("%4.1f\t",$1); matrix=matrix sprintf("%4.1f\t",$1)}matrix= matrix sprintf("%4.1f\t",$3); if((NR-1)%3==0 && NR!=10)matrix=matrix "\n"}END{print header; print matrix}';
            20.5    21.5    22.5
    20.5    -4.1     1.2     7.0
    21.5    -6.2     4.3    10.4
    22.5     0.0     6.0    16.7
    

    Explanations:

    • sort -n ifile.txt sort the file numerically
    • header variable will store all the data necessary to create the header line it is initiated to header="\t" and will be appended with the necessary information thanks to header=header sprintf("%4.1f\t",$1) for lines respecting (NR-1)%3==1)
    • in the same way you construct the matrix using matrix variable: matrix=matrix sprintf("%4.1f\t",$1) will create the first column and matrix= matrix sprintf("%4.1f\t",$3) will populate the matrix with the content then if((NR-1)%3==0 && NR!=10)matrix=matrix "\n" will add the adequate EOL

提交回复
热议问题