【问题标题】:How to sort a text file numerically and then store the results in the same text file?如何对文本文件进行数字排序,然后将结果存储在同一个文本文件中?
【发布时间】:2015-04-23 16:50:45
【问题描述】:

我试过sort -n test.text > test.txt。但是,这给我留下了一个空的文本文件。这是怎么回事,我能做些什么来解决这个问题?

【问题讨论】:

标签: linux


【解决方案1】:

排序不会就地对文件进行排序。它会输出一个排序的副本。

你需要sort -n -k 4 out.txt > sorted-out.txt

编辑:要获得您想要的顺序,您必须使用反向读取的数字对文件进行排序。这样做:

cut -d' ' -f4 out.txt | rev | paste - out.txt | sort -k1 -n | cut -f2- > sorted-out.txt

更多学习-

sort -nk4 file

-n 用于数字排序

-k 用于提供密钥

或添加 -r 选项进行反向排序

sort -nrk4 file

【讨论】:

    【解决方案2】:

    这是因为您正在读取和写入同一个文件。你不能那样做。您可以尝试一些临时文件,如 mktemp 甚至是:

    sort -n test.text > test1.txt
    mv test1.txt test
    

    对于sort,您还可以执行以下操作:

    sort -n test.text -o test.text
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多