sed In-Place Editing Portable Use


Example

In-place editing, while common, is a non-standard feature. A viable alternative would be to use an intermediate file to either store the original, or the output.

sed 'sed commands' > file.out && mv file.out file
# or
mv file file.orig && sed 'sed commands' file.orig > file

To use the -i option with both the GNU and FreeBSD syntax an extension must be specified and appended to the -i option. The following will be accepted by both, and produce two files, the original version at file.orig and the edited version at file:

sed -i.orig 'sed commands' file

See a basic example given a file file:

$ cat file
one
two
three
$ sed -i.orig 's/one/XX/' file
$ cat file                       # the original file has changed its content
XX
two
three
$ cat file.orig                  # the original content is now in file.orig
one
two
three

A more complex example, replacing each line with line number:

$ printf 'one\ntwo\n' | tee file1 | tr a-z A-Z > file2
$ sed -ni.orig = file1 file2
$ cat file1.orig file2.orig
one
two
ONE
TWO
$ cat file1 file2
1
2
1
2

Why a backup file is required

In order to use in-place editing without a backup file, -i must be given a zero-length argument and FreeBSD sed requires an argument to -i, either appended or separate, while the GNU optional argument extension requires the argument be appended to -i. Both support appending the argument to -i, but without it being required -i'' command is indistinguishable from -i extension, and so a zero-length argument can not be appended to -i.