我正在寻找一种简单的方法来找到文件中最长行的长度。理想情况下,它应该是一个简单的bash shell命令,而不是脚本。
当前回答
使用wc (GNU coreutils) 7.4:
wc -L filename
给:
101 filename
其他回答
只是为了好玩,下面是Powershell版本:
cat filename.txt | sort length | select -last 1
为了得到长度:
(cat filename.txt | sort length | select -last 1).Length
如果您正在使用MacOS并得到以下错误: wc:非法选项——L你不需要安装GNU sipmly这样做。
如果你所要做的只是获取文件中最长行的字符数,并且使用OS X运行:
Awk '{打印长度}' "$file_name" | sort -rn | head -1
像这样的东西;
$file_name" $(awk '{打印长度}' "$file_name" | sort -rn | head -1)字符"
输出:
文件my_file中最长的一行有117个字符
使用wc (GNU coreutils) 7.4:
wc -L filename
给:
101 filename
在perl中:
perl -ne 'print ($l = $_) if (length > length($l));' filename | tail -1
这只打印行,不打印它的长度。
以上例子中被忽略的重要一点。
下面两个示例计算展开的选项卡
wc -L <"${SourceFile}"
# or
expand --tabs=8 "${SourceFile}" | awk '{ if (length($0) > max) {max = length($0)} } END { print max }'
以下2个计数为未展开的选项卡。
expand --tabs=1 "${SourceFile}" | wc -L
# or
awk '{ if (length($0) > max) {max = length($0)} } END { print max }' "${SourceFile}"
so
Expanded nonexpanded
$'nn\tnn' 10 5