Finding the max and min values and printing the li

2019-03-18 09:26发布

问题:

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.

max=0
cat file.txt|while read LINE
do
    fir=`echo $LINE|awk '{print $2}'`
    sec=`echo $LINE|awk '{print $3}'`
    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.

回答1:

For min value:

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

For max value:

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


回答2:

Alternatively using sort and sed

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

-n flag - sort as numbers.

How to use it:

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


回答3:

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

$ awk -F, '{a[$1]=$0}END{asorti(a,b);print a[b[1]]"\n"a[b[NR]]}' file
100,red
102,black

If you don't:

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

Alternatively presort and print the first and last line:

$ sort -t',' -nk1 file | awk 'NR==1;END{print}'
100,red
102,black


回答4:

[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

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