問題は、行if (max < $2) max=$2 cmax=$1
とがそれぞれでif (min > $2) min=$2 cmin=$1
ある必要があることです。もう 1 つのエラーは、少なくとも. コードをより適切にフォーマットすると、エラーを見つけやすくなります。if (max < $2){ max=$2; cmax=$1 }
if (min > $2){ min=$2; cmin=$1}
print cmin min \n cmax max
print cmin min "\n" cmax max
BEGIN{
first=1
}
{
if (first) { # We should move this to it's own block and test against NR
max = min = $2
first = 0
next
}
if (max < $2) { # confusing using max to store min
max=$2
cmax=$1
}
if (min > $2) { # and min to store max your operators are the wrong way round
min=$2
cmin=$1
}
}
END {
print cmin min "\n" cmax max
}
スクリプトは動作するはずですが、まだいくつか問題があります。以下のバージョンと比較してください。
NR==1{ # If we are on the first line in the file
min=max=$2 # Set initial min/max values
next # Skip to next line
}
{
if ($2 > max) { # If the value in field 2 is greater than current max
max=$2 # Store the new values
cmax=$1
}
if ($2 < min) { # If the value in field 2 is less than current min
min=$2 # Store the new values
cmin=$1
}
}
END {
# Use printf to properly format the output
printf "%s %d\n%s %d\n",cmin,min,cmax,max
}
補足: 2 番目のフィールドでファイルを事前に並べ替えると、より簡潔になります。
sort -nk2 file | awk 'NR==1{print}END{print}'