Extract minimum/maximum using awk

From the below table I want to print highest value and lowest value using awk script.

aaa 55 66 96 77
ggg 22 96 77 23
ddd 74 58 18 3
kkk  45 89 47 92
zzz  34 58 89 92

Thanks, Green

Try:

awk '
first == "" {
	m = $2
	M = $2
	first = "done"
}
{	for(i = 2; i <= NF; i++) {
		if($i < m) m = $i
		if($i > M) M = $i
	}
}
END {	print m, M
}' table

If you are using a Solaris system, use /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk instead of /usr/bin/awk or /bin/awk .

If table contains your sample input, the output produced is:

3 96

which are the minimum and maximum values in your data (ignoring the 1st column in each line).

1 Like

Just for fun:

awk 'NR==1 || $1==""{next} l=="" || $1<l{l=$1} $1>h{h=$1} END{print l,h}' RS=" " file

Another approach using GNU awk asort function:

xargs -n1 < file | gawk '/^[0-9]*$/{A[NR]=$1}END{n=asort(A);print A[1],A[n]}'