Finding the length of the longest column

Hi,

I am trying to figure out how to get the length of the longest column in the entire file (because the length varies from one row to the other)

I was doing this at first to check how many fields I have for the first row:

awk '{print NF; exit}'  file

Now, I can do this:

awk '{ if (length($0) > max) max = length($0) } END { print max }' file

but that prints the length of the longest line in the file rather than the length of the longest field in the file.

Any help please?

Thanks!

Try

awk '{for (i=1;i<=NF;i++) if (length($i)>max) max=length($i)} END{print max}' file
1 Like

That can do the job if your AWK implementation treats a multicharacter RS as a regular expression and if you set RS to a regular expression which mimicks the default value of FS. In effect, what is usually a field becomes a record.

If your AWK does not support that RS behavior, the same can be accomplished by filtering the file through tr, replacing spaces and tabs with newlines, before piping into AWK.

I'll leave the actual code as an exercise.

Regards,
Alister

1 Like

Hi, in awk $0 is the whole line. If you want only one field of the line you have to check for i=1 to NF.
$0 = $1 + $2 +.....NF. You have to know the length of $1 ,$2.... and compare them. For example with a loop while...while (i<NF) and you have to keep the minor length while the loop checks every field...If you need help with the code ask me for it.

danielos,
I am aware that $0 was the entire line, I used $NF though and it gave me the length of the last column.

Alistar,
That sounds like a good plan, I'll give that a shot!