如何获得在UNIX中每列的最大长度? [英] How to get max length of each column in unix?
问题描述
假设,我有这样的一个源文件。
Suppose, I have a source file like this.
ID|NAME|ADDRESS
1|ABC|PUNE
2|XYZA|MUMBAI
12|VB|NAGPUR
我想获得每列的最大长度(不包括标题名称)。
输出应该是这样的。
2 | 4 | 6
I want to get the maximum length of each column (excluding the header names). Output should be like this. 2|4|6
我已经试过这样的命令。
尾+2名|切-d| -f1 | AWK'{打印长度}'|排序-r | uniq的
I have tried the command like this. tail +2 filename | cut -d"|" -f1 | awk '{ print length }' | sort -r | uniq
这适用于第一列。是否有AWK任何可用的选项,以获取最大长度为每列?
This works for 1st column. Is there any option available in awk to get max length for each column?
在此先感谢您的时间。
推荐答案
这可以做一个一般的方式,让你不必在意你的字段数:长度存储在数组中和保持检查它是否为最大或没有。最后,通过他们循环,并打印结果。
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
请参阅输出:
$ 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)}' a
2|4|6
有关列的数目可变的,我们可以列的最大存储量为例如 COLS
:
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)}' a
2|4|6
这篇关于如何获得在UNIX中每列的最大长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!