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

时间:2021-01-29 04:18:51

How can I print index values using awk or others along with 1st row and 1st column ? thanks

如何使用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 个解决方案

#1


1  

Using awk to print only the main diagonal values of the matrix

使用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

Explained:

解释:

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
}  

#2


1  

awk to the rescue!

拯救!

assuming input file is tab separated

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

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  

Using awk to print only the main diagonal values of the matrix

使用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

Explained:

解释:

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
}  

#2


1  

awk to the rescue!

拯救!

assuming input file is tab separated

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

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