Artificial intelligent assistant

awk: print one line per field-1 value (distinct) where difference "field-2 - field-3" is minimum I want to distinct print the lines where diff is minimum. (diff=$2-$3) The input file is: c1,5,2 <-- diff=3 c1,5,3 <-- diff=2 c1,5,1 <-- diff=4 c2,8,3 <-- diff=5 c2,8,4 <-- diff=4 The expected output is: c1,5,3 c2,8,4 How can I do this with Awk (e.g. with a one-liner)? * * * In other words, for each first field value (c1, c2), I want to print a single line with that first field value, chosen for the minimal diff between the second and third fields.

Enjoy **_awk_** solution:


awk -F, '{ diff=$2-$3; if(a[$1]>diff || !a[$1]) { a[$1]=diff; b[$1]=$2 FS $3 } }
END{ for(i in a) print i,b[i] }' OFS=',' yourfile


The output:


c1,5,3
c2,8,4

xcX3v84RxoQ-4GxG32940ukFUIEgYdPy 5f5b1c4bf8717180414f751c525a79d3