AWK: Compare two columns conditionally in one file

Viewed 197

I have a pipe (|) delimited file where $1 has IDs and there are values in $2 and $3. The file has ~5000 rows in it with each ID $1 repeated multiple times. The file looks like this

a|1|2
a|2|0
a|3|3
a|4|0
b|5|3
b|2|4

I am trying to print lines where the $2 on the current line is <= the max $3 so the output will be

a|1|2
a|2|0
a|3|3
b|2|4

Any lead on this would be highly appreciated! Thank you.

1 Answers

It sounds like you just want to, for each $1, print those lines where $2 is less than or equal to the max $3:

$ cat tst.awk
BEGIN { FS="[|]" }
NR==FNR {
    max[$1] = ( ($1 in max) && (max[$1] > $3) ? max[$1] : $3 )
    next
}
$2 <= max[$1]

$ awk -f tst.awk file file
a|1|2
a|2|0
a|3|3
b|2|4
Related