Dilu
Dilu

Reputation: 119

Biggest and smallest of all lines

I have a output like this

3.69
0.25
0.80
1.78
3.04
1.99
0.71
0.50
0.94

I want to find the biggest number and the smallest number in the above output

I need output like

smallest is 0.25 and biggest as 3.69

Upvotes: 1

Views: 142

Answers (5)

Kaz
Kaz

Reputation: 58500

TXR solution:

$ txr -e '(let ((nums [mapcar tofloat (gun (get-line))]))
            (if nums
              (pprinl `smallest is @(find-min nums) and biggest is @(find-max nums)`)
              (pprinl "empty input")))'
0.1
-1.0
3.5
2.4
smallest is -1.0 and biggest is 3.5

Upvotes: 0

Kalanidhi
Kalanidhi

Reputation: 5092

You can use this method also

sort file  | echo -e `sed -nr '1{s/(.*)/smallest is :\1/gp};${s/(.*)/biggest no is :\1/gp'}`

Upvotes: 0

Sylvain Leroux
Sylvain Leroux

Reputation: 51980

You want an awk solution?

echo "3.69 0.25 0.80 1.78 3.04 1.99 0.71 0.50 0.94" | \
    awk -v RS=' ' '/.+/ { biggest = ((biggest == "") || ($1 > biggest)) ? $1 : biggest;
                         smallest = ((smallest == "") || ($1 < smallest)) ? $1:smallest}
                  END { print biggest, smallest}'

Produce the following output:

3.69 0.25

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85775

Just sort your input first and print the first and last value. One method:

$ sort file | awk 'NR==1{min=$1}END{print "Smallest",min,"Biggest",$0}' 
Smallest 0.25 Biggest 3.69

Upvotes: 3

gump
gump

Reputation: 155

Hope this help.

OUTPUT="3.69 0.25 0.80 1.78 3.04 1.99 0.71 0.50 0.94"
SORTED=`echo $OUTPUT | tr ' ' '\n' | sort -n`
SMALLEST=`echo "$SORTED" | head -n 1`
BIGGEST=`echo "$SORTED" | tail -n 1`

echo "Smallest is $SMALLEST"
echo "Biggest is $BIGGEST"

Added op's awk oneliner request.

I'm not good at awk, but this works anyway. :)

echo "3.69 0.25 0.80 1.78 3.04 1.99 0.71 0.50 0.94" | awk '{
    for (i=1; i<=NF; i++) {
        if (length(s) == 0) s = $i;
        if (length(b) == 0) b = $i;
        if ($i < s) s = $i;
        if (b < $i) b = $i;
    }
    print "Smallest is", s;
    print "Biggest is", b;
}'

Upvotes: 1

Related Questions