【问题标题】:how to print only columns with a specific value如何仅打印具有特定值的列
【发布时间】:2015-07-06 11:51:59
【问题描述】:

我有一个包含列分隔值的文件,第一行在此处显示为具有真实数据的下一行的列标题。实际的列集比本示例中的要长得多,顺便说一句,这就是为什么我想自动化我需要做的工作。

main-cat    ID  AFFIL   PERM    FF  PLAN    
ACA yes EDU yes no  no
ACA yes EDU no  yes no
ACA yes EDU no  no  yes

我需要为每一行提取值不是“no”的那些列。此外,我希望在格式上打印这样一列:

列标题=行值

示例:上面的三个示例行应打印为:

main-cat=ACA ID=yes AFFIL=EDU PERM=yes 
main-cat=ACA ID=yes AFFIL=EDU FF=yes
main-cat=ACA ID=yes AFFIL=EDU PLAN=yes 

我最好的建议是无休止的条件列表(有很多列),说如果column1不是“no”,打印“main-cat =”+row-value,如果column 2不是“no” ,打印“ID=”+行值。但肯定有更有效的方法来实现这一目标吗?我使用 (g)awk 和/或 shell 脚本。 如有任何建议,将不胜感激。

【问题讨论】:

  • 如果所有字段都是“否”,你想打印什么?空行?没有?还有什么?
  • 好吧,我提前知道,有些字段的值总是不是 no。如果不是这种情况,我可能会提醒自己注意这一行:“警告:空行”。

标签: shell awk gawk


【解决方案1】:

我会说

awk 'NR == 1 { split($0, colnames); next } { sep = ""; for(i = 1; i <= NF; ++i) if($i != "no") { printf("%s%s=%s", sep, colnames[i], $i); sep = OFS } print "" }' filename

那是

NR == 1 {                                      # in the first line
  split($0, colnames)                          # remember column names
  next                                         # do nothing else
}
{                                              # in all other lines:
  sep = ""                                     # reset separator token
  for(i = 1; i <= NF; ++i) {                   # wade through fields
    if($i != "no") {                           # for those that aren't "no"
      printf("%s%s=%s", sep, colnames[i], $i)  # print them with the remem-
                                               # bered column name
      sep = OFS                                # set sep to OFS here so that
                                               # the fields will have a
                                               # separator in front, starting
                                               # with the second
    }
  }
  print ""                                     # when done, add newline.
}

【讨论】:

  • 太棒了,正是我需要的!非常感谢!
【解决方案2】:

这对我有用:

NR == 1 {
    for (i = 1; i <= NF; i++) {
        title[i] = $i
    }
    next
}

{
    for (i = 1; i <= NF; i++) {
        if ($i != "no") {
            printf(" %s=%s", title[i], $i)
        }
    }
    printf("\n")
}

根据您的输入文件,它会生成您寻求的输出:

c:\> gawk -f temp.awk temp_in.txt
 main-cat=ACA ID=yes AFFIL=EDU PERM=yes
 main-cat=ACA ID=yes AFFIL=EDU FF=yes
 main-cat=ACA ID=yes AFFIL=EDU PLAN=yes

c:\>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 2021-04-13
    相关资源
    最近更新 更多