我正在寻找一种简单的方法来找到文件中最长行的长度。理想情况下,它应该是一个简单的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"

其他回答

使用wc (GNU coreutils) 7.4:

wc -L filename

给:

101 filename
awk '{print length, $0}' Input_file |sort -nr|head -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

纯粹的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"
awk '{ if (length($0) > max) {max = length($0); maxline = $0} } END { print maxline }'  YOURFILE