0

我试图在一列中找到最大和最小的数字。输出应具有最大和最小数字以及最大和最小数字的名称。

我写的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=$1if (min > $2) min=$2 cmin=$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
}

附注:如果您在第二个字段上对文件进行预排序,则可以更简洁:

sort -nk2 file | awk 'NR==1{print}END{print}' 
于 2013-04-04T14:25:25.900 回答