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 inputfile
This method creates a temporary file, modifies its content, and then replaces the original file with the temporary file.
- 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. - 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.