如何按浮点数对行进行排序

如何按浮点数对行进行排序

我有这样一个文件:

name: xxx --- time: 5.4 seconds
name: yyy --- time: 3.2 seconds
name: zzz --- time: 6.4 seconds
...

现在我想按这些浮点数对该文件进行排序以生成一个新文件,如下所示:

name: yyy --- time: 3.2 seconds
name: xxx --- time: 5.4 seconds
name: zzz --- time: 6.4 seconds
...

我已经尝试过该命令awk '{print $5}' myfile | sort -g,但这只会显示浮点数。

答案1

如果使用 GNUsort或兼容版本,您可以使用其-g开关进行一般数字排序:

$ sort -g -k5,5 file
name: yyy --- time: 3.2 seconds
name: xxx --- time: 5.4 seconds
name: zzz --- time: 6.4 seconds

告诉-k5,5sort 仅对第五列执行排序。

用法

请记住info sort页面中的详细信息:

'-g'
'--general-numeric-sort'
'--sort=general-numeric'
     Sort numerically, converting a prefix of each line to a long
     double-precision floating point number.  *Note 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.

相关内容