我尝试使用Unix sort对这些数字进行排序,但似乎无效:
2e-13
1e-91
2e-13
1e-104
3e-19
9e-99
这是我的命令:
sort -nr file.txt
如何正确地做到这一点?
我尝试使用Unix sort对这些数字进行排序,但似乎无效:
2e-13
1e-91
2e-13
1e-104
3e-19
9e-99
这是我的命令:
sort -nr file.txt
如何正确地做到这一点?
使用-g
(长格式为--general-numeric-sort
)代替-n
。 -g
选项通过strtod
传递数字以获取其值,并将识别此格式。
我不确定这是否适用于所有的sort
实现,还是仅适用于GNU实现。
sort
。这可能会有问题,但我认为只会在非常旧的系统上。 - Tim Post... | LANG=C sort -g
。 - user3132194sort
命令没有-g
选项,还有另一种方法。$ printf "%.200f\n" $(<file) |sort -n |xargs printf "%g\n"
1e-104
9e-99
1e-91
3e-19
2e-13
2e-13
$ sort -g file
1e-104
9e-99
1e-91
3e-19
2e-13
2e-13
$ printf "%.200f\n" `cat file` |sort -n |xargs printf "%g\n"
只需要做两件事:
-g
(或--general-numeric-sort
)使sort
正确处理指数数字。LC_ALL=C
。如果您的数据可能包含除ASCII外的一些语言特定符号,则sort
对区域设置非常敏感。因此,对于您使用sort
的每种情况,使用LC_ALL=C
是通用方法,它使sort
将输入流视为二进制,您将不会遇到任何问题。因此,通用解决方案是:
cat file.txt | LC_ALL=C sort -gr | less
我还在我的.bashrc
文件中为sort创建了一个别名:
alias csort="LC_ALL=C sort"
以便更加方便地使用。
好的,这里是一个未经完全测试的Python脚本版本。预期用法:
sort_script.py file.txt
很不幸,我是在Windows上开发的,并且安装了两个不同版本的Python,因此无法进行适当的测试。警告:需要最新的Python(带有添加或更改的print函数)。注意:back_to_file标志可以作为可选参数,尽管在Unix中您始终可以重定向...即使在Windows中也可以。
#!/usr/bin/env python3.1
# Note: requires newer python
import sys
#Remove this line:
sys.argv = ('', 'file.txt')
assert(len(sys.argv) == 2)
with open(sys.argv[1], 'r') as fin:
lines = fin.readlines()
lines_sorted = sorted(lines, key=lambda x: float(x))
back_to_file = False # Change this if needed
if back_to_file:
with open(sys.argv[1], 'w') as fout:
fout.writelines(lines_sorted)
else:
for lns in lines_sorted:
print(lns, end='') # Suppress new line