How do I prevent sed -i from destroying symlinks?

The -i/--in-place flag edits a file in place. By default, sed reads the given file, processes it outputting into a temporary file, then copies the temporary file over the original, without checking whether the original was a symlink.

GNU sed has a --follow-symlinks flag, which makes it behave as you want:

$ echo "cat" > pet
$ ln --symbolic pet pet_link
$ sed --in-place --follow-symlinks 's/cat/dog/' pet_link
$ cat pet
dog

Tags:

Symlink

Sed