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:
- Use a temporary file:
sed 's/old-text/new-text/g' inputfile > tempfile && mv tempfile inputfileThis method creates a temporary file, modifies its content, and then replaces the original file with the temporary file.
- Use the
-i.bakoption:sed -i.bak 's/old-text/new-text/g' inputfileThe
.bakextension creates a backup file of the original file, and the modified content is saved to the original file. - Use the
readlinkcommand to resolve the symbolic link:file=$(readlink -f inputfile) nsed -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.
