platypus106
platypus106

Reputation: 33

AWK print column from a specific row if conditions are met

I want to use 'awk' to extract specific information from a formatted file such that:

  1. If the row has 2 fields, the first column (100) is printed and the second column (2) represents "X" pairs of lines that follow
  2. If the row corresponding to NR + (2*X -1) starts with a "B" the second column of that row is printed
  3. If the corresponding row to NR + (2*X -1) does not start with a "B" the value "0" is printed.

Example File:

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

Ideal Output:

100 .9
200 0

Code Thus Far:

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

Which produces:

100  
200 

Upvotes: 3

Views: 3311

Answers (3)

Akshay Hegde
Akshay Hegde

Reputation: 16997

Input

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

Output

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

Explanation

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

Upvotes: 4

user31264
user31264

Reputation: 6737

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

Upvotes: 2

Stephen Rauch
Stephen Rauch

Reputation: 49812

Here is some awk code to meet your requirements:

Code:

#!/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
}

Output:

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

Upvotes: 0

Related Questions