> > On Tue, Mar 28, 2017 at 7:13 AM, Ismael Cama <ismael.cama.mou...@gmail.com > > > wrote: > > > When you try to sort a file and write the result in the same file, all > the > > contents are deleted. Example: > > > > sort foo.txt > foo.txt > > > On Tue, Mar 28, 2017 at 9:30 AM, Michael Speer <knome...@gmail.com> wrote:
> This isn't a bug in sort. The ">" redirection operator in your shell opens > and truncates the file to ready it for output before your shell invokes > sort. After sort starts running and opens and reads the foo.txt file, it > finds that empty file and outputs nothing, as you would expect if you had > purposely given an empty file to sort. > > You'll need to use a temporary file in order to avoid this. > > sort foo.txt > foo.txt.tmp ; mv foo.txt.tmp foo.txt One may also use sponge <https://linux.die.net/man/1/sponge>: sort foo.txt | sponge foo.txt Or an awkish equivalent, if one doesn't have moreutils: sponge () { awk '{a[NR] = $0} END {for (i = 1; i <= NR; i++) print a[i]}' }