Grouping using AWK | COL1 and COL3

Viewed 48

I was trying to group col1 based on smallest value on col3, but was unable to do so.

Input:
rs3813193   ENSG00000215914 636821
rs3813193   ENSG00000215790 669121
rs3813193   ENSG00000078808 153810
rs3813193   ENSG00000142609 890192
rs3813193   ENSG00000160075 478552
rs3813193   ENSG00000188290 63024
rs3813193   ENSG00000169885 852139
rs3813193   ENSG00000160072 408663
rs3813193   ENSG00000162576 289570
Desired output:
rs3813193   ENSG00000188290 63024
My code:
awk '$3<min[$1]{min[$1]=$3; row[$1]=$0} END{for (i in row) print row[i]}'

Thank you.

1 Answers

Could you please try following, written based on your shown samples. Tested it on https://ideone.com/MQBYuU

awk '
{
  a[$1]=a[$1]<$3?(a[$1]?a[$1]:$3):$3
  b[$1 OFS $3]=$0
}
END{
  for(j in a){
    print b[j OFS a[j]]
  }
}
' Input_file
Related