How to prevent sed -i command overwriting my symlinks on Linux or Unix

The sed -i command on Linux and Unix systems can overwrite symbolic links (symlinks) if not used with caution. To prevent sed -i from overwriting symlinks, you can use the following methods:

  1. Use a temporary file:
    sed 's/old-text/new-text/g' inputfile > tempfile && mv tempfile inputfile

    This method creates a temporary file, modifies its content, and then replaces the original file with the temporary file.

  2. Use the -i.bak option:
    sed -i.bak 's/old-text/new-text/g' inputfile

    The .bak extension creates a backup file of the original file, and the modified content is saved to the original file.

  3. Use the readlink command to resolve the symbolic link:
    file=$(readlink -f inputfile)
    sed -i 's/old-text/new-text/g' "$file"

    This method resolves the symbolic link to the target file and modifies the content of the target file, rather than the symbolic link.

Using one of these methods will prevent sed -i from overwriting symbolic links.

(www.williamricedental.com)

Leave a Comment