Wednesday, October 15, 2008

Find min max of a column using awk - bash


I already discussed how to find min, max and average using awk in one of my earlier post titled Min,max and average using awk

Here is a simple one liner using awk to find the min and max of a column.

$ cat rank.txt
7.8|awk|S002
8|bash|S124
7.3|sed|S345
6.1|expect|S009
9.0|python|S008
4.1|tcl|S234

The awk one liners:

$ awk 'min=="" || $1 < min {min=$1} END{ print min}' FS="|" rank.txt
4.1

$ awk 'max=="" || $1 > max {max=$1} END{ print max}' FS="|" rank.txt
9.0

$ awk 'min=="" || $1 < min {min=$1; subject=$2}; END{ print min,subject}' FS="|" rank.txt
4.1 tcl

4 comments:

Me and unix said...

hi
i need help with script to find the max time for each server .
my script from the begining :
(i found first the size of each backup ) .

for I in `grep FeIbm3NtLib /tmp/DAY_Sun|awk -F'|' '{print $3}'|sort -u`
do
echo $I
omnirpt -report session_objects -session $I -tab |grep Completed |awk -F'\t' '{print $2,$3,$12,$11}'
done > SundayBackups
1199 more SundayBackups

for Ser in $( FozzieSize
1202 more FozzieSize


for Ser in `awk '{print $1}' FozzieSize |sort -u`
do
echo $Ser
grep -w $Ser SundayBackups|awk '{sum+=$3} END {printf "%5.1f",sum/1024/1024}'|read SundayBackups
echo $Ser $SundayBackups
done > ServerSize

please assits ...

Unknown said...

Excelent!
Implementing it on "Show your desktop" screenshot app. :)
I needed it to figure out how many custom shortcuts a user have in gnome. :)

Unknown said...

@rho con linux , Good to see such a practical use case of Awk ! thanks.

Unknown said...

perl -wMstrict -Mvars='@h' -F'/\|/' -lane '
BEGIN{@h=(
[ sub { @{$h[0]}[1,2] = @_ if $_[0] < ($h[0][1]//"Inf") } ],
[ sub { @{$h[1]}[1,2] = @_ if $_[0] > ($h[1][1]//"-Inf") } ],
)}
$h[$a++%@h][0]->(@F) for 0 .. $#h}{print "@{$_}[1,2]" for @h

' rank.txt

© Jadu Saikia www.UNIXCL.com