我正在寻找一种简单的方法来找到文件中最长行的长度。理想情况下,它应该是一个简单的bash shell命令,而不是脚本。
当前回答
纯粹的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"
其他回答
主题的变化。
它将显示文件中最长行长度的所有行,并保留它们在源代码中出现的顺序。
FILE=myfile grep `tr -c "\n" "." < $FILE | sort | tail -1` $FILE
那么myfile
x
mn
xyz
123
abc
将会给
xyz
123
abc
awk '{ if (length($0) > max) {max = length($0); maxline = $0} } END { print maxline }' YOURFILE
纯粹的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
以上例子中被忽略的重要一点。
下面两个示例计算展开的选项卡
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