Convert column to matrix format using awk

前端 未结 4 2177
有刺的猬
有刺的猬 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:19

    Adjusted my old GNU awk solution for your current input data:

    matrixize.awk script:

    #!/bin/awk -f
    BEGIN { PROCINFO["sorted_in"]="@ind_num_asc"; OFS="\t" }
    NR==1{ next }
    {
        b[$1];               # accumulating unique indices
        ($1 != $2)? a[$1][$2] = $3 : a[$2][$1] = $3; # set `diagonal` relation between different indices 
    }
    END {
        h = "";
        for (i in b) {
            h = h OFS i     # form header columns
        } 
        print h;            # print header column values
        for (i in b) { 
            row = i;        # index column
            # iterating through the row values (for each intersection point)
            for (j in a[i]) {
                row = row OFS a[i][j]
            } 
            print row  
        }
    }
    

    Usage:

    awk -f matrixize.awk yourfile
    

    The output:

        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
    

提交回复
热议问题