awk to find the max

Experts,
Here is my question.
I have got file like below

# cat file
XYZb,24,26,6
XYZc,24,26,6
XYZe,24,25,5
XYZf,23,29,5
XYZi,16,25,5
XYZj,24,26,7
XYZn,17,23,4
XYZz,23,29,5

Now, I want to print the line's Column1[delimitor is ,] whose Column 3 is the max of all.

My code is

awk -F',' 'BEGIN {max = 0;} {if ($3>max) {max=$3;server=$1}} END {print server}' file

But, If there are more than 1 row contain the same max value, my snippet is printing only the last one. Please help.

Here my expected output is XYZf,XYZz.

PS: I want to get this accomplished with awk

try

awk -F, 'BEGIN{max=0}{if($3>max){max=$3;A[max]=A[max]?A[max]","$1:$1}}END{print A[max]}' file

@sathyaonnuix: You're on the right track. Why don't you try to assign $1 to an array and increment that array's index if $3==max ? On new max , reset the index to 1.

@pamu: your proposal yields XYZf with the sample given.

@pamu :

can we change it to

, might get the desired result. Let me know if its true.

---------- Post updated at 05:07 AM ---------- Previous update was at 05:06 AM ----------

thanks RudiC, thats a valid idea. I will get it done.

Better way just change one bracket position in my code..

try with this...

awk -F, 'BEGIN{max=0}{if($3>max){max=$3}; A[max]=A[max]?A[max]","$1:$1}END{print A[max]}' file

Try this:

awk -F, 'NR==FNR{if($3 > m){m=$3}next}$3==m' file file

@Franklin,

Rather retrieving the entire line, I just want to print the column1 with comma separated.

# awk -F, 'NR==FNR{if($3 > m){m=$3}next}$3==m' file file
XYZf,23,29,5
XYZz,23,29,5

---------- Post updated at 07:17 AM ---------- Previous update was at 07:15 AM ----------

@Pamu: Nope, it isn't working

# awk -F, 'BEGIN{max=0}{if($3>max){max=$3}; A[max]=A[max]?A[max]","$1:$1}END{print A[max]}' file
XYZf,XYZi,XYZj,XYZn,XYZz

---------- Post updated at 07:20 AM ---------- Previous update was at 07:17 AM ----------

Thanks to pamu for his original snippet, a small tweak to it, is working. :slight_smile:

# awk -F, 'BEGIN{max=0}{if($3>=max){max=$3;A[max]=A[max]?A[max]","$1:$1}}END{print A[max]}' file
XYZf,XYZz

Try:

awk -F, 'NR==FNR{if($3>m){m=$3}next}$3==m{s=s?s FS $1:$1}END{print s}' file file
1 Like

its works, thanks Franklin. can you explain how file file works in the code.

awk reads the file twice. The condition NR==FNR is true when awk reads the file the first time.