0

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

Jack
  • 25
  • 3

3 Answers3

1
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.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • When I try $3>100 it does not work, do you know why please ? – Jack Jan 15 '21 at 01:57
  • do you know please also how to do If I want to add the condition that the $2 of the 2nd line start by B ? thank you – Jack Jan 15 '21 at 02:04
  • 1) No - must be something different about your data from what you posted, there's nothing magic about the number 100 vs 80. 2) `$2 ~/^B/`. 3) You're welcome! – Ed Morton Jan 15 '21 at 02:56
  • maybe because sometimes numbers are like that [56 ] or [1 ] instead of [56] or [1] – Jack Jan 15 '21 at 03:05
  • None of those differences in the input would affect the calculation. You'd have to post some actual data that the script doesn't work for for me to be able to help you debug the issue. – Ed Morton Jan 15 '21 at 13:28
0

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]
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

A slightly different approach:

awk -F '[][ ]+' '
    $2 == "AA" {
        aa = $0
        getline; getline
        if ($3 > 80) {
            print aa
            print
        }
    }
' file
glenn jackman
  • 238,783
  • 38
  • 220
  • 352