如何在列上grep? (垂直扫描而不是水平扫描)

时间:2022-10-01 08:54:18

Lets say I have a series of values in no particular order:

可以说我有一系列没有特定顺序的值:

Metric1 Metric3 Metric4 Metric5  Metric9  Metric8
Value1  Value3  Value4  Value5  Value9  Value8

What is the best way to grep for Metric5 and spit out that column?

grep Metric5并吐出该列的最佳方法是什么?

For instance

例如

grep Metric5 <file>

Should return

应该回来

Metric5
Value5

2 个解决方案

#1


2  

In general:

一般来说:

awk -v colNames="Metric5 Metric1 Metric9" '
BEGIN { split(colNames,tmp); for (i in tmp) tgts[tmp[i]] }
NR==1 {
    for (i=1; i<=NF; i++) {
        if ($i in tgts) {
            fldNrs[++numTgts] = i
        }
    }
}
{
    for (tgtNr=1; tgtNr<=numTgts; tgtNr++) {
        printf "%s%s", $(fldNrs[tgtNr]), (tgtNr<numTgts ? OFS : ORS)
    }
}
' file
Metric1 Metric5 Metric9
Value1 Value5 Value9

If you just want 1 column selected then obviously just list 1 on the -v assignment

如果您只想选择1列,那么显然只需在-v赋值中列出1

#2


0  

$ cat > foo.awk
{
    for(i=1;i<=NF;i++) {
        a[i][NR]=$i
        if(foo==$i) 
            it=i
} nr=NR
} END {
    if(it!="") 
        for(i=1;i<=nr;i++) 
            print a[it][i]
}
$ awk -v foo="Metric5" -f foo.awk foo
Metric5
Value5

#1


2  

In general:

一般来说:

awk -v colNames="Metric5 Metric1 Metric9" '
BEGIN { split(colNames,tmp); for (i in tmp) tgts[tmp[i]] }
NR==1 {
    for (i=1; i<=NF; i++) {
        if ($i in tgts) {
            fldNrs[++numTgts] = i
        }
    }
}
{
    for (tgtNr=1; tgtNr<=numTgts; tgtNr++) {
        printf "%s%s", $(fldNrs[tgtNr]), (tgtNr<numTgts ? OFS : ORS)
    }
}
' file
Metric1 Metric5 Metric9
Value1 Value5 Value9

If you just want 1 column selected then obviously just list 1 on the -v assignment

如果您只想选择1列,那么显然只需在-v赋值中列出1

#2


0  

$ cat > foo.awk
{
    for(i=1;i<=NF;i++) {
        a[i][NR]=$i
        if(foo==$i) 
            it=i
} nr=NR
} END {
    if(it!="") 
        for(i=1;i<=nr;i++) 
            print a[it][i]
}
$ awk -v foo="Metric5" -f foo.awk foo
Metric5
Value5