Linux 查找最大值和最小值并从文件中打印该行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16212410/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:47:53  来源:igfitidea点击:

Finding the max and min values and printing the line from a file

linuxbashshellunixawk

提问by hackio

I have a file which has numbers at the first column.

我有一个文件,第一列有数字。

100,red
101,blue
102,black

I should write a shell script that it will print the line with the max and min numbers.

我应该编写一个 shell 脚本,它将打印带有最大和最小数字的行。

max=0
cat file.txt|while read LINE
do
    fir=`echo $LINE|awk '{print }'`
    sec=`echo $LINE|awk '{print }'`
    if [ $fir -gt $max ]; then
       max=$fir
    fi
    if [ $sec -gt $max ];then
        max=$sec
    fi
done

grep $max file.txt

This is what i tried so far for finding the max.

这是我迄今为止为找到最大值而尝试的方法。

回答by Chris Seymour

You should just do the whole thing in awkif you have GNU awk:

你应该只是做整个事情中awk,如果您有GNU awk

$ awk -F, '{a[]=
$ awk -F, 'NR==1{s=m=}{a[]=
$ sort -t',' -nk1 file | awk 'NR==1;END{print}'
100,red
102,black
;m=(>m)?:m;s=(<s)?:s}END{print a[s]"\n"a[m]}' file 100,red 102,black
}END{asorti(a,b);print a[b[1]]"\n"a[b[NR]]}' file 100,red 102,black

If you don't:

如果你没有:

[bash]$ cat log
100,red
101,blue
102,black
[bash]$ all=( $(sort log | cut -f1 -d',') )
[bash]$ echo "MIN: ${all[0]} and MAX: ${all[${#all[@]}-1]}"
MIN: 100 and MAX: 102


Alternatively presort and print the first and last line:

或者预先排序并打印第一行和最后一行:

$ sort -n id | sed -n '1p;$p'
100 red
102 black

回答by abasu

$ a=($(sort -n id | sed -n '1s/^\([0-9]\+\).*$//p;$s/^\([0-9]\+\).*$//p'))
$ echo "min=${a[0]}, max=${a[1]}"
min=100, max=102

Create an array using the sorted elements. First and last elements are containing the min and max values

使用排序的元素创建一个数组。第一个和最后一个元素包含最小值和最大值

回答by loentar

Alternatively using sort and sed

或者使用 sort 和 sed

[bash]$ cut -f1 -d"," file_name | sort -n | head -1

-nflag - sort as numbers.

-n标志 - 按数字排序。

How to use it:

如何使用它:

[bash]$ cut -f1 -d"," file_name | sort -n | tail -1

回答by alind

For min value:

对于最小值:

##代码##

For max value:

对于最大值:

##代码##

回答by Ali Ait-Bachir

In zip CSV file

在 zip CSV 文件中

For the Min value

对于最小值

bzcat file.csv.bz2 | cut -f2 -d";" | sort -n | head -2

bzcat file.csv.bz2 | cut -f2 -d";" | sort -n | head -2

For the max value

对于最大值

bzcat file.csv.bz2 | cut -f2 -d";" | sort -n | tail -1

bzcat file.csv.bz2 | cut -f2 -d";" | sort -n | tail -1

Regadrs,

各位,

Ali

阿里