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

Yve*_*ves 7 sort numeric-data

我有这样一个文件:

name: xxx --- time: 5.4 seconds
name: yyy --- time: 3.2 seconds
name: zzz --- time: 6.4 seconds
...
Run Code Online (Sandbox Code Playgroud)

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

name: yyy --- time: 3.2 seconds
name: xxx --- time: 5.4 seconds
name: zzz --- time: 6.4 seconds
...
Run Code Online (Sandbox Code Playgroud)

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

slm*_*slm 10

如果使用 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
Run Code Online (Sandbox Code Playgroud)

-k5,5排序告诉就只是第5列进行排序。

用法

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

'--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.
Run Code Online (Sandbox Code Playgroud)

  • 请注意,对于像 `3.2` 这样的数字,标准的 `sort -n` 就足够了(前提是语言环境的基数字符是 `.`)。对于 1e20、0x20、inf... 等数字,您需要使用 `-g` GNU 扩展名。 (6认同)
  • 必须使用“LC_ALL=C sort -g ...”才能让我的排序工作。 (4认同)