coreutils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Is the command `sort input.txt -o input.txt` OK?


From: Bob Proulx
Subject: Re: Is the command `sort input.txt -o input.txt` OK?
Date: Sat, 15 Mar 2014 11:57:40 -0600
User-agent: Mutt/1.5.22 (2013-10-16)

Peng Yu wrote:
> `sort input.txt -o input.txt` overwrites the input file. My
> understanding is that sort reads everything and then write the output.
> So it is OK to overwrite the original file. But I want to be sure. Can
> anyone confirm if this is the case? Thanks.

Yes.  Using -o is how you sort a file in place.  This is the
traditional Unix sort behavior.  The GNU sort documentation says:

  -o OUTPUT-FILE
  --output=OUTPUT-FILE
     Write output to OUTPUT-FILE instead of standard output.  Normally,
     `sort' reads all input before opening OUTPUT-FILE, so you can
     safely sort a file in place by using commands like `sort -o F F'
     and `cat F | sort -o F'.

And so -o is the correct option to sort in place.  However note it also
says:

     However, `sort' with `--merge' (`-m') can open the output file
     before reading all input, so a command like `cat F | sort -m -o F
     - G' is not safe as `sort' might start writing `F' before `cat'
     is done reading it.

Do not use with -m!

     On newer systems, `-o' cannot appear after an input file if
     `POSIXLY_CORRECT' is set, e.g., `sort F -o F'.  Portable scripts
     should specify `-o OUTPUT-FILE' before any input files.

For maximum safety you should always set -o before any input files.
As in the documented example.  Your example had options last.  Instead
for maximum safety and portability you should place the option first.

  sort -o file.txt file.txt

Bob



reply via email to

[Prev in Thread] Current Thread [Next in Thread]