awk: find minimum and maximum in column

a non-awk answer:

cut -d" " -f1 file |
sort -n |
tee >(echo "min=$(head -1)") \
  > >(echo "max=$(tail -1)")

That tee command is perhaps a bit much too clever. tee duplicates its stdin stream to the files names as arguments, plus it streams the same data to stdout. I'm using process substitutions to filter the streams.

The same effect can be used (with less flourish) to extract the first and last lines of a stream of data:

cut -d" " -f1 file | sort -n | sed -n '1s/^/min=/p; $s/^/max=/p'

or

cut -d" " -f1 file | sort -n | { 
    read line
    echo "min=$line"
    while read line; do max=$line; done
    echo "max=$max"
}

Awk guesses the type.

String "10" is less than string "4" because character "1" comes before "4". Force a type conversion, using addition of zero:

min=`awk 'BEGIN{a=1000}{if ($1<0+a) a=$1} END{print a}' mydata.dat`
max=`awk 'BEGIN{a=   0}{if ($1>0+a) a=$1} END{print a}' mydata.dat`

Tags:

Bash

Awk