如何过滤所选列和行中的值?

时间:2017-07-11 13:30:56

标签: awk

如何使用ids.1文件中的行名和ids.2文件中的列名过滤输入文件中的值?

示例输入

name    s1  s2  s3  s4
a1  7   8   7   8
a2  7   54  7   8
a3  8   8   8   8
a4  7   7   7   0

ids.1

name
a1
a4

ids.2

name
s3
s4

示例输出

name    s3  s4
a1  7   8
a4  7   0

我使用以下代码过滤所选行的值。我怎样才能将它扩展到列?

awk 'ARGIND == 1 { a[$1] = 1; next } a[$1] { print $0 }' ids.1 sample.input


name    s1      s2      s3      s4
a1      7       8       7       8
a4      7       7       7       0

2 个答案:

答案 0 :(得分:2)

更简单,更快的版本:

awk '
ARGIND==1{row[$1]=1;next}
ARGIND==2{col[$1]=1;next}
row[$1]{
    for(i=1;i<=NF;i++){
        if(col[$i] && FNR==1) v[i]=1
        if (v[i]) printf "%s%s", (i==1?"":FS), $i
    }
    print ""
} ' id.1 id.2 data.file

用你的例子,它给出了:

name  s3  s4    
a1    7   8   
a4    7   0 

答案 1 :(得分:1)

这假设第一条记录始终位于列文件(ids.2)中:

$ awk '
ARGIND==1 {                  # first file, rows
    r[$1]
} 
ARGIND==2 {                  # second file, columns
    c[$1]
} 
ARGIND==3 && FNR==1 {        # first record of third file, data
    n=split($0,a)            # split the first record to a, the column template
    for(i in a)              # delete the cols we don t want
        if((a[i] in c)==0)
            delete a[i]
}ARGIND==3 && $1 in r {      # third file and the rows we want
    b=""                     # print buffer
    for(i=1;i<=NF;i++)       # for all cols
    if(i in a)               # get the ones we want
        b=b (b==""?"":OFS) $i
    print b                  # output
}' ids.1 ids.2 file
name s3 s4
a1 7 8
a4 7 0