Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 487
hackio Avatar asked Apr 25 '13 10:04

hackio


People also ask

Which command can give you the number of lines in a file called file in the current directory?

The wc command is used to find out the number of lines and number of words. A variable is created to hold the file path.

Which Unix command will return the maximum from a list of numbers as a input?

grep -Eo '[0-9]+' file prints all matches of positive decimal integer numbers in the file. Each match will be printed in a different line, as per the -o flag. sort -rn sorts the list numerically and in reverse, so that the first number is the biggest.


1 Answers

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
like image 56
alind Avatar answered Oct 19 '22 07:10

alind