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?
You can use Vim in Ex mode:
%
select all linesx
save and closeThe problem with the command
is that
file
is truncated by the shell before sed actually gets to process it. As a result, you get an empty file.The sed way to do this is to use
-i
to edit in place, as other answers suggested. However, this is not always what you want.-i
will create a temporary file that will then be used to replace the original file. This is problematic if your original file was a link (the link will be replaced by a regular file). If you need to preserve links, you can use a temporary variable to store the output of sed before writing it back to the file, like this:Better yet, use
printf
instead ofecho
sinceecho
is likely to process\\
as\
in some shells (e.g. dash):With all due respect to the above correct answers, it's always a good idea to "dry run" scripts like that, so that you don't corrupt your file and have to start again from scratch.
Just get your script to spill the output to the command line instead of writing it to the file, for example, like that:
OR
This way you can see and check the output of the command without getting your file truncated.
You should try using the option
-i
for in-place editing.And the
ed
answer:To reiterate what codaddict answered, the shell handles the redirection first, wiping out the "input.html" file, and then the shell invokes the "sed" command passing it a now empty file.
This does a global in-place substitution on the file index.html. Quoting the string prevents problems with whitespace in the query and replacement.