Muhammad Ahmad
Muhammad Ahmad

Reputation: 25

What is causing this code/command to not work when comparing negative numbers?

awk '($6>max) && ($4!="AZ") {max = $6; line = $0}END{print line}' foo.txt

Whenever field #6 contains negative numbers, it doesn't correctly return the line that has the highest number in field 6.

The goal is to for example in the following file contents:

Shellstrop Eleanor Phoenix AZ 85023 -2920765
Shellstrop Donna Tarantula_Springs NV 89047 -5920765
Mendoza Jason Jacksonville FL 32205 -4123794
Mendoza Douglas Jacksonville FL 32209 -3193274 (Donkey Doug)
Peleaz Steven Jacksonville FL 32203 -3123794 (Pillboi)

goal is to return the line containing Peleaz. (It wouldn't be Shellstrop Eleanor as she lives in AZ.) Instead it returns a newline

This works as required for positive numbers but not negative. So I don't understand, surely if it works for positive numbers it can't be completely wrong. Or there could be some completely different bug Im missing. Im very new to awk.

awk '($6>max) && ($4!="AZ") {max = $6; line = $0}END{print line}' foo.txt

Expected line with Peleaz Steven Jacksonville to return. Returns newline instead.

Upvotes: 2

Views: 54

Answers (1)

anubhava
anubhava

Reputation: 785481

You must also check for condition when max is not set:

awk '
(max == "" || $6 > max) && $4 != "AZ" {
   max = $6
   line = $0
}
END {
   print line
}' file

Peleaz Steven Jacksonville FL 32203 -3123794 (Pillboi)

Upvotes: 3

Related Questions