Hi I want to replace document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
with
(function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();
in all occurrences...
So i used this below code.
find /cygdrive/c/xampp/htdocs/news -type f -exec sed -i s#document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));#(function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();#g {} \;
But it is not replacing. Is there any problem in escaping ?
Thanks
You need to quote the argument to sed, and escape any nested quotes. Otherwise this:
s#document.write(unescape("%3Cscript src='" + gaJsHost + ...
will be broken into separate words by the shell, instead of being passed as a single argument to sed.
You need to surround the entire sed script (the s#from#to#
part) in quotes, I would choose single quotes, then replace every '
in the script with \'
.
(Also, why are you using find -exec
instead of what I suggested?)
Well, the first step would be to check the sed
command alone:
bash: syntax error near unexpected token `('
You have to put the sed command into single or double quotes so it is passed as a single parameter to the sed application 's#docum....'
. If you have single quotes within single quotes, or double quotes within double quotes you have to escape it.
Note that the command will look quite ugly, not really readable or maintainable, I would use python or ruby where you have special quotes which will help overcome with the problems of string escaping...
sed -i "s/^document.write(unescape(.*;$/(function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();/" example.txt
Even if it's not a direct answer, for such replacement you can use "rpl" tool.
It looks like you're using cygwin, thus you can find a win32 port here.