如果满足条件,则AWK从特定行打印列

时间:2017-02-17 05:29:39

标签: bash awk gawk

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

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

    100 .9
    200 0
    

    理想输出:

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

    远远的代码:

    100  
    200 
    

    产生:

        resize_canvas(&C, 5, 6, 5, 10, 'e');
    

3 个答案:

答案 0 :(得分:4)

<强>输入

$ 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

答案 1 :(得分:2)

NF==2 {x=$1; rec=NR+2*$2-1}
NR==rec {y=0; if ($1=="B") y=$2; print(x,y)}

答案 2 :(得分:0)

以下是一些满足您要求的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