我试图在一列中找到最大和最小的数字。输出应具有最大和最小数字以及最大和最小数字的名称。
我写的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 }
你能帮我指出一下这段代码的问题是什么吗?
答案 0 :(得分:2)
问题是行if (max < $2) max=$2 cmax=$1
和if (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}'