如何确定“最大数字”,以便 sort -n 始终将其放在最后?我正在考虑Inf
一些语言中的一些东西,但我不确定是否存在这样的排序。
背景是我正在按年龄对可能不存在的路径列表进行排序,以便
存在先行,从新到旧,
不存在的走最后。
我正在使用装饰方法并试图惩罚那些未出生的孩子:
INFINITY=99999999999999 # ...close enough, right?
age_of() {
if [ -e $1 ];
then
local ctime=$(stat -c %Z "$1" 2>/dev/null)
local now=$(date +%s)
echo $(($now - $ctime))
else
echo $INFINITY
fi
}
cat - \
| while read path;
do
echo "$(age_of $path) $path"
done \
| sort -n \
| cut -d\ -f 2-
Run Code Online (Sandbox Code Playgroud)
但显然评论很幼稚;即使 99999999999999 也不够接近,这只是时间问题。;)
那么 INFINITY 有更好的价值吗?
不是 POSIX 解决方案,但 GNU sort 提供了-g
支持更广泛的数字规范(包括无穷大)的选项。来自http://www.gnu.org/software/coreutils/manual/html_node/sort-invocation.html -
‘-g’
‘--general-numeric-sort’
‘--sort=general-numeric’
Sort numerically, converting a prefix of each line to a long double-precision
floating point number. See Floating point. Do not report overflow, underflow, or
conversion errors. Use the following collating sequence:
Lines that do not start with numbers (all considered to be equal).
NaNs (“Not a Number” values, in IEEE floating point arithmetic) in a
consistent but machine-dependent order.
Minus infinity.
Finite numbers in ascending numeric order (with -0 and +0 equal).
Plus infinity.
Use this option only if there is no alternative; it is much slower than
--numeric-sort (-n) and it can lose information when converting to floating
point.
Run Code Online (Sandbox Code Playgroud)
从我自己的测试来看,任何以Inf
(大写/小写的任意组合)开头的行似乎都将出现在任何数字之后。
如果失败,我认为没有任何字符序列可以使用sort -n
. GNU sort 似乎首先将所有其他序列视为零,将负数放在后面但在正数之前。如果是正在排序的时间戳,您可以做的是使用 64 位时间戳的最大值加一:
9,223,372,036,854,775,808
Run Code Online (Sandbox Code Playgroud)
这比你开始时多几个数字!