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
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
.