Variable and awk inside for loop

Thanks all for taking time out and reading this thread and big Thanks to all who have come forward for rescue.

Background: I have a variable "nbrofcols" that has number of columns from a data file. Now, using this count in for loop, I am trying to get the maximum length of each column present inside the file. And, I am passing the file name at run time.

This is the file am passing at run time.

COLUMN_A|COLUMN_B|COLUMN_C
001|AAAAAA|YUYWD
002|ABCOHFOHNFN|DLDLULDNSFHCLYHNDJK
003|BCXSOHNSN|XCDFHNSH
004|ZBDIWUFHOJKSJF|DGFTSVVCD
005|ZXSEDTRWEF|XCDFHNSHDGFTSVVCD

This is what I have done so far:

nbrofcols=`head -1 $1 | awk -F'|' '{print NF;}'`
cat /dev/null > nbrofcols.txt
for ((i = 1; i <= $nbrofcols; i++));
do
  awk 'NR>1' $1 | awk -F"|" ' length("$i") > len { len=length("$i") } END { print len } ';
done >> nbrofcols.txt
:

Expected Output

COLUMN_A: 3
COLUMN_B: 14
COLUMN_C: 19

Note: Awk works on a file as a stand alone but not able to get it working in for loop.

Any help would be greatly appreciated.

You don't really need a variable to store number of columns. You can use the built-in variable NF instead:-

awk -F\| '
        NR == 1 {
                for ( i = 1; i <= NF; i++ )
                        hdr_col = $i
        }
        NR > 1 {
                for ( i = 1; i <= NF; i++ )
                        max_col = ( length($i) > max_col ? length($i) : max_col )
        }
        END {
                for ( i = 1; i <= NF; i++ )
                        print hdr_col ":" max_col
        }
' filename

Thanks Yoda for such a quick response.

However, I am getting syntax error in line # 8. Also, could you please explain line # 8?

Much appreciated!

What is the error??

(also, if you're using Solaris, use nawk or /usr/xpg4/bin/awk)

This is the error I am getting.

awk: syntax error near line 8
awk: illegal statement near line 8

And the OS you're using?

SunOS apiaifodb01 5.10 Generic_150400-52 sun4u sparc SUNW,SPARC-Enterprise

Thank you. Please refer to post #4.