Find longest string and print it

Hello all,

I need to find the longest string in a select field and print that field.

I have tried a few different methods and I always end up one step from where I need to be.

Methods thus far:

nawk '{if (length($1) > long) long=length($1); if(length($1)==long) print $1}'

The above print my desired result and a few other lines. I have been thinking of a way I could have a variable that holds only the largest value then test that value against lenght($1) and print $1 if they are equal but I have had no luck.

I have also tried placing all the length($1) values into an array, sorting and printing the array but I am short one step which is to take the first values in the array (the highest value) and test it against length($1) and print $1 if they are equal.

nawk '{a[NR]=length($1);  print a[NR] | "sort +0nr -2 +2d"}' 

I apologize if my logic is a bit messy, this is my 5th day playing with nawk.
Thanks in advance

Is this what you're looking for?

awk '!len || length($1) > len {len=length($1)} END{print len}' file
1 Like

This is very close. Based on one of the prior code I managed to put together, the final step would be taking this output and using it in the following manner.

Theoretically speaking.

awk '!len || length($1) > len {len=length($1)} END{print len}' file
result
awk '{if (length($1) == result) print $1}' 

I will try this with via a for loop, the final index of len or a pipe once I am awake and let you know what the final code looks like.

Thank you Franklin.

If you want to print the longest field you could do something like:

awk '!len || length($1) > len {len=length($1);s=$1} END{print s, len}' file

Yes, this is what I was trying to do.

Can you please break down the logic for me?
Primarily the

 !len || 

If the variable len is 0 or is "".

Thank you