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


当前回答

我在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"

其他回答

以上例子中被忽略的重要一点。

下面两个示例计算展开的选项卡

  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
perl -ne 'print length()."  line $.  $_"' myfile | sort -nr | head -n 1

打印最长行的长度、行号和内容

perl -ne 'print length()."  line $.  $_"' myfile | sort -n

打印所有行的排序列表,包括行号和长度

. 是连接运算符-它在这里用在length()之后 美元。当前行号是多少 $_是当前行

awk '{ if (length($0) > max) {max = length($0); maxline = $0} } END { print maxline }'  YOURFILE 

只是为了好玩,下面是Powershell版本:

cat filename.txt | sort length | select -last 1

为了得到长度:

(cat filename.txt | sort length | select -last 1).Length

我在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"