我正在寻找一种简单的方法来找到文件中最长行的长度。理想情况下,它应该是一个简单的bash shell命令,而不是脚本。


当前回答

主题的变化。

它将显示文件中最长行长度的所有行,并保留它们在源代码中出现的顺序。

FILE=myfile grep `tr -c "\n" "." < $FILE | sort | tail -1` $FILE

那么myfile

x
mn
xyz
123
abc

将会给

xyz
123
abc

其他回答

wc -L < filename

给了

101

使用wc (GNU coreutils) 7.4:

wc -L filename

给:

101 filename

看起来所有的答案都没有给出最长的行号。以下命令可以给出行号和大致长度:

$ cat -n test.txt | awk '{print "longest_line_number: " $1 " length_with_line_number: " length}' | sort -k4 -nr | head -3
longest_line_number: 3 length_with_line_number: 13
longest_line_number: 4 length_with_line_number: 12
longest_line_number: 2 length_with_line_number: 11

我在Unix环境中,使用gzip压缩的文件,大小只有几gb。我使用一个记录长度为2052的2 GB gzip文件测试了以下命令。

zcat < gzipped文件- > |厕所

and

Zcat <gzip文件> | awk '{打印长度}' | sort -u

时间是平均的

117秒 109秒

这是我运行10次后的脚本。

START=$(date +%s) ## time of start

zcat $1 |  wc -L

END=$(date +%s) ## time of end
DIFF=$(( $END - $START ))
echo "It took $DIFF seconds"

START=$(date +%s) ## time of start

zcat $1 |  awk '{print length}' | sort -u

END=$(date +%s) ## time of end
DIFF=$(( $END - $START ))
echo "It took $DIFF seconds"

纯粹的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"