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?
use sed's -i option, e.g.
If you have a link to be added, try this. Search for the URL as above (starting with https and ending with.com here) and replace it with a URL string. I have used a variable
$pub_url
here.s
here means search andg
means global replacement.It works !
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.
The 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):I was searching for the option where I can define the line range and found the answer. For example I want to change host1 to host2 from line 36-57.
You can use gi option as well to ignore the character case.