[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
bug#26279: sort bug
From: |
Bishop Bettini |
Subject: |
bug#26279: sort bug |
Date: |
Tue, 28 Mar 2017 12:06:40 -0400 |
>
> On Tue, Mar 28, 2017 at 7:13 AM, Ismael Cama <address@hidden
> >
> 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 <address@hidden> 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]}'
}