Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Print minimum value in column

Status
Not open for further replies.

gborrageiro

Technical User
Feb 26, 2008
2
0
0
GB
hello,

I'm having trouble printing the minimum numerical value in a column. When I try printing the maximum value it works fine. It's almost as if awk does'nt like the '<' parameter.

The command I run is:
cat file | awk '$5 < min {min=$5; minline=$0}; END{ print min, minline}'

The result is just blank. I know column 5 is right because this returns correct values:
cat file | awk '{ print $5 }'

your help is appreciated.

regards
G
 
It's because min starts off like a 0

So nothing is lower

Try adding something like
Code:
BEGIN { min = 999 }

but keep in mind that this is a bit of a kludge. If the lowest value is actually 1000 then it will print 999. So pick a big number, or to do it properly set min to the first value of $5 on the first line.

Gotta get a coffee so I'll leave that up to you :)
 
min has no value when your script starts, so awk treats it as 0. Presumably none of the numbers in column 5 are negative, so your $5 < min never evaluates to true.

Try adding NR==1 { min=$5 } to the beginning of your script to initialise it.

Incidentally, you don't need to cat file, just use awk 'script' file.

Annihilannic.
 
Hi

Annihilannic said:
min has no value when your script starts, so awk treats it as 0.
Correct, in case of arithmetic operations. But in string operations it is treated as empty string. Taking advantage of this, an alternative solution is :
Code:
awk '[red]min=="" ||[/red] $5 < min {min=$5; minline=$0}; END{ print min, minline}' file


Feherke.
 
You're both putting my dodgy solution to shame.

Wish I'd delayed that coffee now :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top