There is also insitu, allowing any commands to be used in-place.
–
sr_Jan 22 '12 at 10:19

@sr_, that's an interesting command, but it doesn't work with any command, only ones that write no faster than they read (otherwise it'll clobber the input file before the command reads it). There's no guarantee that it'll work with sort.
–
cjmJan 22 '12 at 11:09

@cjm, I'm really not sure, but isn't this supposed to handle that case?
–
sr_Jan 22 '12 at 13:39

@sr_, I think you're right. I read the description instead of looking at the source. Although for really big files, it might run out of memory for the buffer and crash (it doesn't look like it checks for a NULL return from malloc).
–
cjmJan 22 '12 at 14:02

2 Answers
2

sort has the -o, --output option that take a filename as argument. If it is the same as the input files, it write the result to a temporary file, then overwrite the original input file (somewhat as sed do).

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.

Only in those rare cases where you can't recreate the original file with the same permissions do I recommend overwriting the file in place. In this case, you'd better save the original input somewhere. And then you can simply process the copy of the input and send it into the original file.