如何在awk中获取列名?

3
我有一个数据文件,格式如下:

Program1, Program2, Program3, Program4
0,        1,        1,        0
1,        1,        1,        0

列是程序名称,行是程序的功能。我需要编写一个awk循环,遍历每一行,检查值是否等于1,然后返回列名并将其放入“results.csv”文件中。所需输出应为:

Program2, Program3
Program1, Program2, Program3

我尝试过这段代码,但它无法工作:

awk -F, '{for(i=1; i<=NF; i++) if ($i==1) {FNR==1 print$i>>results}; }'

非常感谢帮助!

(保留HTML标签)
3个回答

5
awk -F', *' '
NR==1 {for(i=1;i<=NF;i++) h[i]=$i; next}
{
    sep="";
    for(x=1;x<=NF;x++) {
        if($x) {
            printf "%s%s", sep, h[x]; 
            sep=", ";
        }
    }
    print ""
}' file

输出:

Program2, Program3
Program1, Program2, Program3

谢谢!这个方法可行,但是每一行的最后一个字段包含了最后一个程序名称,原因不明。使用if($x==1)代替if($x)解决了这个问题。 - TmpuV

1
$ cat tst.awk
BEGIN { FS=", *" }
NR==1 { split($0,a); next }
{
    out = ""
    for (i=1; i<=NF; i++)
         out = out ($i ? (out?", ":"") a[i] : "")
    print out
}

$ awk -f tst.awk file
Program2, Program3
Program1, Program2, Program3

0

我的看法比较冗长,但应该可以处理尾随逗号。虽然不是一行代码。

BEGIN {                                                                     
    # Formatting for the input and output files.
    FS = ", *"
    OFS = ", "
}

FNR == 1 {
    # First line in the file
    # Read the headers into a list for later use.
    for (i = 1; i <= NF; i++) {
        headers[i] = $i
    }
}

FNR > 1 {
    # Print the header for each column containing a 1.
    stop = 0
    for (i = 1; i <= NF; i++) {
        # Gather the results from this line.
        if ($i > 0) {
            stop += 1
            results[stop] = headers[i]
        }
    }
    if (stop > 0) {
        # If this input line had no results, the output line is blank
        for (i = 1; i <= stop; i++) {
            # Print the appropriate headers for this result.
            if (i < stop) {
                # Results other than the last
                printf("%s%s", results[i], OFS)
            } else {
                # The last result
                printf("%s", results[i])
            }
        }
    }
    printf("%s", ORS)
}

将此保存为类似于script.awk的文件,然后运行它,例如:

awk -f script.awk infile.txt > results

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接