I have a file temp.txt, that I want to sort with the sort
command in bash.
I want the sorted results to replace the original file.
This doesn't work for example (I get an empty file):
sortx temp.txt > temp.txt
Can this be done in one line without resorting to copying to temporary files?
EDIT: The -o
option is very cool for sort
. I used sort
in my question as an example. I run into the same problem with other commands:
uniq temp.txt > temp.txt.
Is there a better general solution?
Tobu's comment on sponge warrants being an answer in its own right.
To quote from the moreutils homepage:
However,
sponge
suffers from the same problem Steve Jessop comments on here. If any of the commands in the pipeline beforesponge
fail, then the original file will be written over.Uh-oh,
my-important-file
is gone.I like the
sort file -o file
answer but don't want to type the same file name twice.Using BASH history expansion:
grabs the current line's first arg when you press enter.
A unique sort in-place:
grabs the last arg in the current line.