I would like to run a find and replace on an HTML file through the command line.
My command looks something like this:
sed -e s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html > index.html
When I run this and look at the file afterward, it is empty. It deleted the contents of my file.
When I run this after restoring the file again:
sed -e s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html
The stdout
is the contents of the file, and the find and replace has been executed.
Why is this happening?
Right-click the document file the content of which you want to replace. Press the Alt key and select Operations > Replace with File... from the menu bar. Locate and select the file that you want to use for replacing the original file content. Click OK.
By default sed does not overwrite the original file; it writes to stdout (hence the result can be redirected using the shell operator > as you showed).
When the shell sees > index.html
in the command line it opens the file index.html
for writing, wiping off all its previous contents.
To fix this you need to pass the -i
option to sed
to make the changes inline and create a backup of the original file before it does the changes in-place:
sed -i.bak s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html
Without the .bak the command will fail on some platforms, such as Mac OSX.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With