使用awk基于行名和列名在矩阵中打印索引值

时间:2016-10-18 22:46:27

标签: matrix awk

如何使用awk或其他第1行和第1列打印索引值?感谢

> input
name s1 s2 s3 s4
g1  2  3  4 5
g2  1  1  1 6
g3  2  2  2 7
g4  2  2  2 10


> output
g1 s1 2
g2 s2 1
g3 s3 2
g4 s4 10

2 个答案:

答案 0 :(得分:1)

awk救援!

假设输入文件是制表符分隔

awk -F'\t' 'NR==1{split($0,h);next} 
                 {for(i=2;i<=NF;i++) print $1,h[i],$i}' file.tsv

g1 s1 2
g1 s2 3
g1 s3 4
g1 s4 5
g2 s1 1
g2 s2 1
g2 s3 1
g2 s4 6
g3 s1 2
g3 s2 2
g3 s3 2
g3 s4 7

答案 1 :(得分:1)

使用awk仅打印矩阵的主对角线值

$ awk 'NR==1 { split($0,x); next } NF>=NR { print $1,x[NR],$NR }' matrix
g1 s1 2
g2 s2 1
g3 s3 2
g4 s4 10

说明:

NR==1 { split($0,x);next }   # split first record to array x for outputing s col
NF>=NR {                     # test for overflow if an asymmerical matrix
    print $1,x[NR],$NR       # output
}