stack
stack

Reputation: 841

How to get the largest value in line

In my project, the content of jobinfo.txt is:

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

I want to find the maxinum value of column 3, so i write a bb.sh, some content like this:

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

It can display 840 in my terminal screen successfully, but in maxscalejobinfo.txt, there is nothing.

I can use in command line like this:

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

and get the correct result:

3123919 nscc1564_ZZG 840

I have tried in bb.sh:

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

but it failed again

I tried another way in bb.sh:

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

it worked OK

what is wrong with bb.sh script? who can help me?

Upvotes: 2

Views: 60

Answers (2)

stack0114106
stack0114106

Reputation: 8711

You can use sort command and redirect the output to 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

Since this resembles SQL, you could do it with sqlite as well

$ 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

Upvotes: 1

anubhava
anubhava

Reputation: 785058

Just use a single awk for this instead of shell + awk:

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

Also make sure jobinfo.txt doesn't have DOS line ending by using:

cat -A jobinfo.txt

If you note ^M in the end of each line then convert that file to Unix file first using dos2unix or sed or tr

Upvotes: 3

Related Questions