How to get max length of each column in unix?
This can be a general way to do it, so that you don't have to care about the number of fields you have: store the lengths in an array and keep checking if it is the maximum or not. Finally, loop through them and print the results.
awk -F'|' 'NR>1{for (i=1; i<=NF; i++) max[i]=(length($i)>max[i]?length($i):max[i])} END {for (i=1; i<=NF; i++) printf "%d%s", max[i], (i==NF?RS:FS)}' file
See output:
$ awk -F'|' 'NR>1{for (i=1; i<=NF; i++) max[i]=(length($i)>max[i]?length($i):max[i])} END {for (i=1; i<=NF; i++) printf "%d%s", max[i], (i==NF?RS:FS)}' a2|4|6
For variable number of columns, we can store the maximum amount of columns in for example cols
:
$ awk -F'|' 'NR>1{cols=(cols<=NF?NF:cols); for (i=1; i<=NF; i++) max[i]=(length($i)>max[i]?length($i):max[i])} END {for (i=1; i<=cols; i++) printf "%d%s", max[i], (i==cols?RS:FS)}' a2|4|6
This might work for you (but if there are many fields I'd use for
cycle and an array to store the length of fields...):
awk -F '|' 'NR>1 {if ( length($1) > l1 ) { l1=length($1) } if ( length($2) > l2 ) { l2=length($2) } if ( length($3) > l2 ) { l3=length($3) } } END { print l1 "|" l2 "|" l3 }' INPUTFILE