我正在寻找一种简单的方法来找到文件中最长行的长度。理想情况下,它应该是一个简单的bash shell命令,而不是脚本。
当前回答
wc -L < filename
给了
101
其他回答
如果您正在使用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 -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
纯粹的POSIX shell解决方案,没有无用的cat使用,也没有外部命令的分叉。以filename作为第一个参数:
#!/bin/sh
MAX=0 IFS=
while read -r line; do
if [ ${#line} -gt $MAX ]; then MAX=${#line}; fi
done < "$1"
printf "$MAX\n"
使用wc (GNU coreutils) 7.4:
wc -L filename
给:
101 filename
在perl中:
perl -ne 'print ($l = $_) if (length > length($l));' filename | tail -1
这只打印行,不打印它的长度。