如何在一列数字中找到最接近 $VariableNumber
的 5 个数字?
例如,如果 $VariableNumber
= 30 那么:
输入文件示例:
50
100
70
40
20
10
65
41
92
示例输出:
20
40
41
10
50
之前有人在其他地方发布了一个答案,它在特定行的特定列中找到与给定值最接近的数字匹配,如下所示:
awk -v col_num="3" -v value="$Number" '
func abs(x) { return (x<0) ? -x : x }
{
distance = abs($col_num - value)
}
NR==1 || distance<shortest_distance {
shortest_distance = distance
nearest_value = $col_num
}
END {
print nearest_value
}
'
但是我一直没能适应
最佳答案
我只是按到 n 的距离对条目进行排序,然后选择第一个条目,例如:
awk -v n=30 '
function abs(x) {return x < 0 ? -x : x}
{print abs($0 - n) "\t" $0}' < file |
sort -n |
head -n 5 |
cut -f 2-
关于text-processing - 找到最接近的前 5 个,而不仅仅是最接近的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38420539/