如何获得最大的价值

时间:2018-12-28 03:30:55

标签: shell

在我的项目中,jobinfo.txt的内容为:

3124631 nsgk138_LZH 48
3123498 nscc1697_ZJK 48
3115687 nsgg135_MJ 48
3123919 nscc1564_ZZG 840
3115689 nsgg135_MJ 48
3115690 nsgg135_MJ 48
3122716 nscc128_ZW 24
3122720 nscc128_ZW 24
3123868 nsgg038_PM 24
3122726 nscc128_ZW 24

我想找到第3列的最大值,所以我写了一个bb.sh,内容如下:

sendzabbixnum=`awk '{print $3}' jobinfo.txt |  sort -n  | uniq | tail -1`
echo $sendzabbixnum
awk '{if($3==$sendzabbixnum) print $0}' jobinfo.txt >> maxscalejobinfo.txt

它可以在我的终端屏幕上成功显示840,但是在maxscalejobinfo.txt中什么都没有。

我可以在命令行中这样使用:

awk '{if($3==840) print $0}' jobinfo.txt

并获得正确的结果:

3123919 nscc1564_ZZG 840

我已经尝试过bb.sh:

awk '{if($3=="$sendzabbixnum") print $0}' jobinfo.txt >> maxscalejobinfo.txt

但是又失败了

我在bb.sh中尝试了另一种方法:

awk '{if($3==840) print $0}' jobinfo.txt >> maxscalejobinfo.txt

效果很好

bb.sh脚本有什么问题?谁可以帮助我?

2 个答案:

答案 0 :(得分:3)

为此只需使用一个awk,而不是shell + awk:

awk '$NF > max {max=$NF; r=$0} END{print r > "maxscalejobinfo.txt"}' jobinfo.txt

还要使用以下命令确保jobinfo.txt的DOS行结尾:

cat -A jobinfo.txt

如果在每行末尾都记下^M,则首先使用dos2unixsedtr将该文件转换为Unix文件

答案 1 :(得分:1)

您可以使用sort命令并将输出重定向到maxscalejobinfo.txt

$ cat  jobinfo.txt
3124631 nsgk138_LZH 48
3123498 nscc1697_ZJK 48
3115687 nsgg135_MJ 48
3123919 nscc1564_ZZG 840
3115689 nsgg135_MJ 48
3115690 nsgg135_MJ 48
3122716 nscc128_ZW 24
3122720 nscc128_ZW 24
3123868 nsgg038_PM 24
3122726 nscc128_ZW 24

$ sort -k3 -nr jobinfo.txt | head -n 1
3123919 nscc1564_ZZG 840

由于它类似于SQL,因此您也可以使用sqlite进行

$ cat ./sqllite_longline.sh
#!/bin/sh
sqlite3 << EOF
create table t1(a,b,c);
.separator ' '
.import $1 t1
select * from t1 where t1.c=(select max(c) from t1)
EOF

$ ./sqllite_longline.sh jobinfo.txt
3123919 nscc1564_ZZG 840
相关问题