Jack
Jack

Reputation: 25

using awk with conditions on different lines

If 2 lines after the line with "AA", $3 of the line is > 80(here 89 so yes) , I want to cat the line with "AA" and "CC".

aaaaaaaa AA [15]
bbbbbbbb BB [60]
cccccccc CC [89]
dddddddd DD [52]

I tried this :

gawk '{for (I=1;I<NF;I++) if ($I == "AA" && $I+2 > 80) print $I,$I+2}' ~/Desktop/toto.txt

output desired :

aaaaaaaa AA [15]
cccccccc CC [89]

Thank you for your help

Upvotes: 0

Views: 98

Answers (3)

glenn jackman
glenn jackman

Reputation: 247202

A slightly different approach:

awk -F '[][ ]+' '
    $2 == "AA" {
        aa = $0
        getline; getline
        if ($3 > 80) {
            print aa
            print
        }
    }
' file

Upvotes: 0

anubhava
anubhava

Reputation: 786091

This should also work:

awk '{val = $3; gsub(/[^0-9]+/, "", val)} prno && NR == prno+2 && val > 80 {print p ORS $0} $2 == "AA" {prno = NR; p = $0}' file

aaaaaaaa AA [15]
cccccccc CC [89]

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 204558

awk -F'[[ ]+' '$2=="AA"{prev=$0; nr=NR+2} (NR==nr) && ($3 >80){print prev ORS $0}' file
aaaaaaaa AA [15]
cccccccc CC [89]

or:

$ awk -F'[[ ]+' '$2=="AA"{prev=$0; c=3} (c&&!--c) && ($3>80){print prev ORS $0}' file
aaaaaaaa AA [15]
cccccccc CC [89]

See Printing with sed or awk a line following a matching pattern for an explanation of c&&!--c and related examples.

Upvotes: 1

Related Questions