2012-09-26 76 views
6

在使用wc -L的Linux命令中,可以获取文本文件最长行的长度。最短线的长度?

如何查找文本文件最短行的长度?

+0

http://superuser.com/q/135753/109661 – hovanessyan

回答

11

试试这个:

awk '{print length}' <your_file> | sort -n | head -n1 

此命令获取长度的所有文件,对它们进行分类(正常,如数字)和,fianlly,打印到控制台的最小数目。

10

纯awk的解决方案:

awk '(NR==1||length<shortest){shortest=length} END {print shortest}' file 
+0

这似乎稍快。 – ADTC

0

我把awk命令到一个函数(对于bash):

function shortest() { awk '(NR==1||length<shortest){shortest=length} END {print shortest}' $1 ;} ## report the length of the shortest line in a file

将此添加到我的.bashrc(然后是“源的.bashrc “)

然后运行它:最短的”yourFileNameHere“

[~]$ shortest .history 
2

它可被分配给一个变量(注意所需的backtics):

[~]$ var1=`shortest .history` 
[~]$ echo $var1 
2 

对于csh:

alias shortest "awk '(NR==1||length<shortest){shortest=length} END {print shortest}' \!:1 "

0

从上方不处理这两种awk解决方案 '\ R' wc -L的方式。 对于单行输入文件,它们不应产生大于wc -L报告的最大行长度的值。

这是一个新sed基于溶液(I无法同时保持正确的缩短):

echo $((`sed 'y/\r/\n/' file|sed 's/./#/g'|sort|head -1|wc --bytes`-1)) 

这里有一些样品中,示出了 '\ R' 如权利要求并证明sed溶液:

$ echo -ne "\rABC\r\n" > file 
$ wc -L file 
3 file 
$ awk '{print length}' file|sort -n|head -n1 
5 
$ awk '(NR==1||length<shortest){shortest=length} END {print shortest}' file 
5 
$ echo $((`sed 'y/\r/\n/' file|sed 's/./#/g'|sort|head -1|wc --bytes`-1)) 
0 
$ 
$ echo -ne "\r\r\n" > file 
$ wc -L file 
0 file 
$ echo $((`sed 'y/\r/\n/' file|sed 's/./#/g'|sort|head -1|wc --bytes`-1)) 
0 
$ 
$ echo -ne "ABC\nD\nEF\n" > file 
$ echo $((`sed 'y/\r/\n/' file|sed 's/./#/g'|sort|head -1|wc --bytes`-1)) 
1 
$