問題是行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
。錯誤被easierly發現,當你格式化更好的代碼:
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}'
會有所幫助,如果你**編輯你的問題**提供樣品的輸入,從樣品預期輸出,電流輸出或錯誤消息。祝你好運。 – shellter 2013-04-04 14:23:42