我正在寻找一种简单的方法来找到文件中最长行的长度。理想情况下,它应该是一个简单的bash shell命令,而不是脚本。
当前回答
看起来所有的答案都没有给出最长的行号。以下命令可以给出行号和大致长度:
$ 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
其他回答
看起来所有的答案都没有给出最长的行号。以下命令可以给出行号和大致长度:
$ 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
wc -L < filename
给了
101
如果您正在使用MacOS并得到以下错误: wc:非法选项——L你不需要安装GNU sipmly这样做。
如果你所要做的只是获取文件中最长行的字符数,并且使用OS X运行:
Awk '{打印长度}' "$file_name" | sort -rn | head -1
像这样的东西;
$file_name" $(awk '{打印长度}' "$file_name" | sort -rn | head -1)字符"
输出:
文件my_file中最长的一行有117个字符
以上例子中被忽略的重要一点。
下面两个示例计算展开的选项卡
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
主题的变化。
它将显示文件中最长行长度的所有行,并保留它们在源代码中出现的顺序。
FILE=myfile grep `tr -c "\n" "." < $FILE | sort | tail -1` $FILE
那么myfile
x
mn
xyz
123
abc
将会给
xyz
123
abc