1833795 Members
3289 Online
110063 Solutions
New Discussion

Find MIN and MAX

 
SOLVED
Go to solution
Ralf Buchhold
Regular Advisor

Find MIN and MAX

Hello
i want to find out the min and max form:
01.01.05 3106 3279
02.01.05 3105 3279
03.01.05 3105 3279
04.01.05 3113 3279
05.01.05 3114 3279
06.01.05 3116 3279
07.01.05 3116 3279
08.01.05 3114 3279
09.01.05 3114 3279
10.01.05 3114 3279
11.01.05 3117 3279
12.01.05 3120 3280
13.01.05 3121 3280
14.01.05 3125 3281
15.01.05 3124 3281
16.01.05 3121 3281
17.01.05 3121 3281
18.01.05 3123 3281
19.01.05 3125 3282
20.01.05 3127 3270
21.01.05 3127 3271
22.01.05 3134 3273

In this example:
MIN1=3105
MAX1=3134
MIN2=3270
MAX2=3282
Thanks
Ralf
5 REPLIES 5
Stephen Keane
Honored Contributor

Re: Find MIN and MAX

Use sort -n -k

then head -1 for min and tail -1 for max.

Where keydef determines which field (column) you are sorting on
Peter Godron
Honored Contributor
Solution

Re: Find MIN and MAX

Ralf,
how about:
#!/usr/bin/sh
echo "top = `sort -k$1,$1n $2 | head -1 | cut -d' ' -f$1`"
echo "min = `sort -k$1,$1rn $2 | head -1 | cut -d' ' -f$1`"

if saved as a.sh and the data is in a.dat
./a.sh 2 a.dat [ for the second field ]
./a.sh 3 a.dat [ for the third field ]

Regards
Stephen Keane
Honored Contributor

Re: Find MIN and MAX

If data is in fred

# MIN1=`cat fred | sort -n -k2,2 | head -1 | awk '{ print $2 }'`
# MAX1=`cat fred | sort -n -k2,2 | tail -1 | awk '{ print $2 }'`
# echo $MIN1
3105
# echo $MAX1
3134
# MIN2=`cat fred | sort -n -k3,3 | head -1 | awk '{ print $3 }'`
# MAX2=`cat fred | sort -n -k3,3 | tail -1 | awk '{ print $3 }'`
# echo $MAX2
3282
# echo $MIN2
3270
Elmar P. Kolkman
Honored Contributor

Re: Find MIN and MAX

If you're using awk anyway, why not:

awk 'NR==1 { min1=$2; max1=$2;min2=$3;max2=$3}
{ if (min1 > $2) { min1 = $2 }
if (min2 > $3) { min2 = $3 }
if (max1 < $2) { max1 = $2 }
if (max2 < $3) { max2 = $3 }
}
END { printf "Min1=%d Max1=%d\nMin2=%d Max2=%d\n",min1,max1,min2,max2 }'
Every problem has at least one solution. Only some solutions are harder to find.
Peter Godron
Honored Contributor

Re: Find MIN and MAX

Ralf,
did these answers solve your problem?
If not can you please update the thread.

Please assign points and close the thread, identifying the solution.
Many Thanks