Finding longest line in a Record

Good Morning/Afternoon All,

I am using the nawk utility in korn shell to find the longest field and display that result.

My Data is as follows:

The cat ran
The elephant ran
Milly ran too
We all ran

I have tried nawk '{ if (length($1) > len) len=length($1); print $1}' filename

The logic I am trying to implement is if the length of $1 is greater than my variable len then assign that value to len and if a larger value is found replace the previous value in len with that value and finally print the value in that variable.

By chance would I be better off with a for loop here?
Or a for with a nested if that that matter?

The latest idea I had was to put length($1) in an array, sort it from highest to lowest and simply print the first value in the array since it will always be the highest but that seems like a waste of resources.

Thanks in Advance for the assistance

Is this a homework assignment?

Could this help you?

len=3
awk -v l=$len 'length($1)>l { l=length($1);rec=$0} END {print l," ", rec}' inputfile
1 Like

No, I am preparing for a technical portion of an interview where my knowledge of nawk scripting will be tested.

Its not $1, its $0 - small change to what you have posted

awk -v l=0 'length($0)>l { l=length($0);rec=$0} END {print l," ", rec}' inputfile
1 Like

Many thanks, I'll play with this a bit.