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