sort
has the -o
(or --output
) option that takes a filename as argument.
The program writes the data to a temporary file,
then overwrites the original input file after the sort is complete
(which can happen only after all the input data have been read).
(This is essentially the same thing as what sed -i
does.)
From GNU sort
info page:
-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
. 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.
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.
and from
The Open Group Base Specifications Issue 7:
-o output
Specify the name of an output file to be used instead of the standard
output. This file can be the same as one of the input files.
There have been reports that
sort
might discard (i.e., destroy)
some or all of your data
if you are out of disk space or out of disk quota,
or the system crashes while
sort
is writing the output file,
or some other error occurs.
In short, to sort a file in place, the following may be used:
sort -o filename filename
insitu
, allowing any commands to be used in-place.sort
.