【问题标题】:AWK print column from a specific row if conditions are met如果满足条件,AWK 从特定行打印列
【发布时间】:2017-02-17 15:04:13
【问题描述】:

我想使用 'awk' 从格式化文件中提取特定信息,例如:

  1. 如果该行有 2 个字段,则打印第一列 (100),第二列 (2) 表示后面的“X”行对
  2. 如果对应于 NR + (2*X -1) 的行以“B”开头,则打印该行的第二列
  3. 如果 NR + (2*X -1) 的对应行不以“B”开头,则打印值“0”。

示例文件:

100 2
A .5 .4
.3 .2 .1    
B .9 .8
.7 .6 .65
200 1
A .5 .4
.3 .2 .1

理想输出:

100 .9
200 0

迄今为止的代码:

awk '{if(NF==2) print $1;}'

产生:

100  
200 

【问题讨论】:

  • 你应该展示你已经尝试过的东西。
  • 我不是 awk 专家,但请在您的帖子中包含该信息。它将帮助某人确定如何帮助您。

标签: bash awk gawk


【解决方案1】:

输入

$ cat f
100 2
A .5 .4
.3 .2 .1    
B .9 .8
.7 .6 .65
200 1
A .5 .4
.3 .2 .1

输出

$ awk 'NF==2{t=$1; l=(NR+2*$2-1)}NR==l{print t,/^B/?$2:0}' f
100 .9
200 0

说明

awk 'NF==2{                    # If row has 2 fields
             t=$1              # lets save 1st field and print later 
             l=(NR+2*$2-1)     # line to be checked
     }
     NR==l{            # if current record number is equal to l

             # Print t, if starts with B then field 2 to be printed else 0 
             print t,/^B/?$2:0
     }
     ' f

【讨论】:

    【解决方案2】:
    NF==2 {x=$1; rec=NR+2*$2-1}
    NR==rec {y=0; if ($1=="B") y=$2; print(x,y)}
    

    【讨论】:

      【解决方案3】:

      这里有一些awk 代码可以满足您的要求:

      代码:

      #!/bin/awk -f
      {
          # skip some lines if needed
          if (to_skip-- > 0) next;
      
          # if we don't have a header, keep the section number as record count
          if (! have_header) {
              header = $1;
              have_header = 1
      
              # skip some records
              to_skip = $2 * 2 - 2;
              next;
          }
      
          # if the first character is a 'B' get the second column    
          if ($1 == "B")
              value = $2;
          else
              value = 0
      
          # print the output, move to the next header
          print header, value
          have_header = 0;
          to_skip = 1
      }
      

      输出:

      $ awk -f test.awk data.txt
      100 .9
      200 0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-28
        • 1970-01-01
        • 1970-01-01
        • 2019-02-09
        • 2017-04-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多