我正在寻找一种简单的方法来查找文件中最长行的长度。理想情况下,它将是一个简单的 bash shell 命令而不是脚本。
14 回答
使用 wc (GNU coreutils) 7.4:
wc -L filename
给出:
101 filename
awk '{print length, $0}' Input_file |sort -nr|head -1
供参考:查找文件中最长的行
awk '{ if (length($0) > max) {max = length($0); maxline = $0} } END { print maxline }' YOURFILE
Just for fun and educational purpose, the pure POSIX shell solution, without useless use of cat and no forking to external commands. Takes filename as first argument:
#!/bin/sh
MAX=0 IFS=
while read -r line; do
if [ ${#line} -gt $MAX ]; then MAX=${#line}; fi
done < "$1"
printf "$MAX\n"
wc -L < filename
给
101
perl -ne 'print length()." line $. $_"' myfile | sort -nr | head -n 1
打印最长行的长度、行号和内容
perl -ne 'print length()." line $. $_"' myfile | sort -n
打印所有行的排序列表,包括行号和长度
.
是连接操作符——这里用在length()之后
$.
是当前行号
$_
是当前行
看起来所有的答案都没有给出最长行的行号。以下命令可以给出行号和大致长度:
$ 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
上述示例中被忽略的重要一点。
以下 2 个示例计算扩展选项卡
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}"
所以
Expanded nonexpanded
$'nn\tnn' 10 5
在 perl 中:
perl -ne 'print ($l = $_) if (length > length($l));' filename | tail -1
这只会打印行,而不是它的长度。
我在 Unix 环境中,使用大小为几 GB 的 gzip 压缩文件。我使用记录长度为 2052 的 2 GB gzip 压缩文件测试了以下命令。
zcat <gzipped file> | wc -L
和
zcat <gzipped file> | awk '{print length}' | 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"
只是为了好玩,这是 Powershell 版本:
cat filename.txt | sort length | select -last 1
为了得到长度:
(cat filename.txt | sort length | select -last 1).Length
主题的变化。
这将显示文件中找到的最长行长度的所有行,并保留它们在源中出现的顺序。
FILE=myfile grep `tr -c "\n" "." < $FILE | sort | tail -1` $FILE
所以我的文件
x
mn
xyz
123
abc
会给
xyz
123
abc
如果您使用的是 MacOS 并收到此错误:
wc: illegal option -- L
您不需要安装 GNU sipmly 执行此操作。
如果您只想获取文件最长行中的字符数并且您正在使用 OS X 运行:
awk '{print length}' "$file_name" | sort -rn | head -1
像这样的东西;
echo "The longest line in the file $file_name has $(awk '{print length}' "$file_name" | sort -rn | head -1) characters"
输出:
The longest line in the file my_file has 117 characters