0

1 つの列で最大値と最小値を見つけようとしていました。出力には、最大数と最小数の名前とともに、最大数と最小数が含まれている必要があります。

私が書いた awk コードは次のとおりです。

 BEGIN{first=1;}
     {if (first) { max = min = $2; first = 0; next;}
     if (max < $2) max=$2 cmax=$1 ; if (min > $2) min=$2 cmin=$1; }
END { print cmin min \n cmax max }

このコードの問題点を指摘するのを手伝ってくれませんか?

4

1 に答える 1

2

問題は、行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 maxprint 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}' 
于 2013-04-04T14:25:25.900 に答える