AWK获取非零值的列

时间:2020-12-16 21:24:19

Any better idea to get columns / fields having non zero values.

更好的想法是让列/字段具有非零值。

Data

数据

      col1 col2 col3 .... col50
      1      0   1         1

so output should be

所以输出应该是

    col1  col3 .... col50
    1       1         1

Edit: Example was wrong, so edited it.

编辑:示例错误,因此编辑它。

2 个解决方案

#1


1  

awk to the rescue!

拯救!

this should handle multiple rows as well...

这应该处理多行......

$ awk 'NR==1{split($0,h); next} 
     NR==FNR{for(i=1; i<=NF; i++) if($i!=0) cols[i]; next}              
            {for(i=1; i<=NF; i++) if(i in cols) printf "%s", $i OFS; 
             print ""}' file{,} | column -t

col1  col3  col50
1     1     1

#2


1  

In awk, more generic solution for multiple records. On the first go it checks for cols with 1s, on the second it outputs records with 1s:

在awk中,针对多个记录的更通用的解决方案。在第一步它检查cols与1s,在第二次它输出记录与1s:

$ cat program.awk 
NR>1 && NR==FNR {                             # find columns to output, build a arr on 1
    for(i=1;i<=NF;i++) 
        if($i) a[i]
    next
} 
sub(/1/,"1") {                                # output only records with 1s
    split($0,b," ")                           # split record to b arr
    for(i=1;i<=NF;i++) 
    if(i in a)                                # print on a arr
        printf "%s%s", b[i], (i==NF?ORS:OFS)
}

Data:

数据:

$ cat data.txt
col1 col2 col3 col4
0 0 0 0
1 0 1 0
0 0 1 1

Run it:

运行:

$ awk -f program.awk data.txt data.txt
col1 col3 col4
1 1 0
0 1 1

#1


1  

awk to the rescue!

拯救!

this should handle multiple rows as well...

这应该处理多行......

$ awk 'NR==1{split($0,h); next} 
     NR==FNR{for(i=1; i<=NF; i++) if($i!=0) cols[i]; next}              
            {for(i=1; i<=NF; i++) if(i in cols) printf "%s", $i OFS; 
             print ""}' file{,} | column -t

col1  col3  col50
1     1     1

#2


1  

In awk, more generic solution for multiple records. On the first go it checks for cols with 1s, on the second it outputs records with 1s:

在awk中,针对多个记录的更通用的解决方案。在第一步它检查cols与1s,在第二次它输出记录与1s:

$ cat program.awk 
NR>1 && NR==FNR {                             # find columns to output, build a arr on 1
    for(i=1;i<=NF;i++) 
        if($i) a[i]
    next
} 
sub(/1/,"1") {                                # output only records with 1s
    split($0,b," ")                           # split record to b arr
    for(i=1;i<=NF;i++) 
    if(i in a)                                # print on a arr
        printf "%s%s", b[i], (i==NF?ORS:OFS)
}

Data:

数据:

$ cat data.txt
col1 col2 col3 col4
0 0 0 0
1 0 1 0
0 0 1 1

Run it:

运行:

$ awk -f program.awk data.txt data.txt
col1 col3 col4
1 1 0
0 1 1