How can I select lines in reason of a value in awk?
Question: Let's assume I have a file which structure looks like this:

    
    
    AAAA 700 something1 something_else1
    AAAA 98 something2 something_else2
    AAAA 2000 something3 something_else3
    BBBB 200 something4 something_else4
    BBBB 21 something5 something_else5
    BBBB 300 something6 something_else6
    

I need to extract, for each value in column $1, the whole line having the
highest value in column $1. This means that, for the field AAAA, I would need
to print the line in which $2=2000. The output should thus look like:

    
    
    AAAA 2000 something3 something_else3
    BBBB 300 something6 something_else6
    

I did it with python, but the file is huge and the process is very time-
consuming. Is there any way to do it with awk?


Answer: 
    $ cat tst.awk
    $1!=prev { if (rec!="") print rec; max=$2; rec=$0 }
    $2 > max { max=$2; rec=$0 }
    { prev=$1 }
    END { if (rec!="") print rec }
    
    $ awk -f tst.awk file
    AAAA 2000 something3 something_else3
    BBBB 300 something6 something_else6
    

The above assumes the `$1` values are always grouped together as shown in your
sample input. Given that, it only stores 1 record in memory at a time (since
you say your input file is huge that could be important), prints the records
in the same order they were read, will work even for zero or negative `$2`
values, and will not output anything for an empty input file.

