Issue
I am executing a shell script where i should replace string in a file. So of course i am using sed
for that. The string is something like:
<!--replace-->
<script src="1.js"></script>
<script src="2.js"></script>
<!--/replace-->
This should be replaced with:
<script src="3.js"></script>
So i am trying to do it as follows:
$ sed "s/<\!--replace-->.\*<\!--\/replace-->/<script src=\"3.js\"><\/script>/g" file.html
But this does not do the trick. What am i missing?
UPD: Removing \n
from file is not a solution in this case, simply because file should be readable.
Solution
The problem is related to newlines, you can change your regex to match newlines, or remove newlines
using tr
:
user@machine:/tmp$ cat s.txt
<!--replace-->
<script src="1.js"></script>
<script src="2.js"></script>
<!--/replace-->
user@machine:/tmp$ tr "\n" " " < s.txt | sed "s#<\!--replace-->.*<\!--/replace-->#<script src="3.js"></script>#g"
<script src=3.js></script>
In case you do not want to remove the newlines, you can :
a) Try a solution using SED as mentioned here: how to tell sed "dot match new line"
b) use perl or python to replace the multiline regex,with s
modifier , the newlines will be intact :
user@mmmm:/tmp$ cat s.txt
<!--replace-->
<script src="1.js"></script>
<script src="2.js"></script>
<!--/replace-->
Dummy content containing
newlines for test.
user@mmmm:/tmp$ perl -i -pe 'BEGIN{undef $/;} s#<\!--replace-->.*<\!--/replace-->#<script src="3.js"></script>#gsm' s.txt
user@mmmm:/tmp$ cat s.txt
<script src="3.js"></script>
Dummy content containing
newlines for test.
Answered By - DhruvPathak Answer Checked By - Mildred Charles (WPSolving Admin)