如何使用 Linux bash shell 脚本从文件中获取最大数量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18072173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get max number from a file with Linux bash shell scripts
提问by Eman
How to get the maximum "rate" and the corresponding "log2c" value from a file as follows? e.g: the max rate is 89.5039 , and log2c 3.0 . thanks a lot.
如何从文件中获取最大“速率”和相应的“log2c”值,如下所示?例如:最大速率是 89.5039 和 log2c 3.0 。多谢。
log2c=5.0 rate=88.7619
log2c=-1.0 rate=86.5412
log2c=11.0 rate=86.1482
log2c=3.0 rate=89.5039
log2c=-3.0 rate=85.5614
log2c=9.0 rate=81.4302
回答by devnull
Use sort
:
使用sort
:
sort -t= -nr -k3 inputfile | head -1
For the given input, it'd return:
对于给定的输入,它会返回:
log2c=3.0 rate=89.5039
If you want to read the values into variables, you can use the builtin read
:
如果要将值读入变量,可以使用内置函数read
:
$ IFS=$' =' read -a var <<< $(sort -t= -nr -k3 inputfile | head -1)
$ echo ${var[1]}
3.0
$ echo ${var[3]}
89.5039
回答by Will Vousden
For very large files, using sort
will be quite slow. In this case, it's better to use something like awk, which needs only one pass:
对于非常大的文件,使用sort
会很慢。在这种情况下,最好使用像 awk 这样的东西,它只需要一次传递:
$ awk -F= 'BEGIN { max = -inf } { if ( > max) { max = ; line = ##代码## } } END { print line }' test.txt
log2c=3.0 rate=89.5039
The time complexity of this operation is linear, while the space complexity is constant (and small). Explanation:
这个操作的时间复杂度是线性的,而空间复杂度是常数(而且很小)。解释:
awk -F= '...' test.txt
: Invoke awk on test.txt, using=
as the field separatorBEGIN { max = -inf }
: Initialisemax
to something that will always be smaller than whatever you're reading.{ if ($3 > max) { max = $3; line = $0; } }
: For each input line, ifmax
is less than the value of the third field ($3
), then update it and remember the value of the current line ($0
)END { print line }
: Finally, print the line we remembered while reading the input.
awk -F= '...' test.txt
: 在 test.txt 上调用 awk,=
用作字段分隔符BEGIN { max = -inf }
:初始化max
为始终比您正在阅读的内容小的内容。{ if ($3 > max) { max = $3; line = $0; } }
: 对于每一行输入,如果max
小于第三个字段的值($3
),则更新并记住当前行的值($0
)END { print line }
: 最后,打印我们在读取输入时记住的行。