Why doesn't “sort file1 > file1” work?

前端 未结 7 1489
忘了有多久
忘了有多久 2020-12-03 21:23

When I am trying to sort a file and save the sorted output in itself, like this

sort file1 > file1;

the contents of the file1 is getting

7条回答
  •  無奈伤痛
    2020-12-03 22:04

    The first command doesn't work (sort file1 > file1), because when using the redirection operator (> or >>) shell creates/truncates file before the sort command is even invoked, since it has higher precedence.

    The second command works (sort file1 | tee file1), because sort reads lines from the file first, then writes sorted data to standard output.

    So when using any other similar command, you should avoid using redirection operator when reading and writing into the same file, but you should use relevant in-place editors for that (e.g. ex, ed, sed), for example:

    ex '+%!sort' -cwq file1
    

    or use other utils such as sponge.

    Luckily for sort there is the -o parameter which write results to the file (as suggested by @Jonathan), so the solution is straight forward: sort -o file1 file1.

提交回复
热议问题