8

在 Linux 命令中使用wc -L它可以获得文本文件最长行的长度。

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

4

4 回答 4

13

试试这个:

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

此命令获取所有文件的长度,对它们进行排序(正确地,作为数字),最后将最小的数字打印到控制台。

于 2012-09-26T11:09:57.393 回答
11

纯awk解决方案:

awk '(NR==1||length<shortest){shortest=length} END {print shortest}' file
于 2012-09-26T11:17:40.807 回答
1

我将 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 (然后是 "source .bashrc" )

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

[~]$ 最短的 .history
2

可以将它分配给一个变量(注意需要反引号):

[~]$ var1=`最短的.history`
[~]$ 回声 $var1
2

对于 csh:

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

于 2015-06-04T13:45:14.787 回答
1

上面的两种awk解决方案都不能像处理 '\r' 那样wc -L处理。对于单行输入文件,它们生成的值不应大于wc -L.

这是一个基于新sed的解决方案(我无法在保持正确的同时缩短):

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
$ 
于 2015-12-15T00:41:01.517 回答