开发者

Replacing string in textfile with quotes and doublequotes with sed

开发者 https://www.devze.com 2023-01-21 13:24 出处:网络
Lets say I want to replace the following string within a textfile: document.write(unescape(\"%3Cscript src=\'\" + \\ + \"google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E\"));

Lets say I want to replace the following string within a textfile:

document.write(unescape("%3Cscript src='" + \ + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

I came up with this sed command, but surprisingly nothing happens at all.

sed -i "s/document.write(unescape(\"%3Cscript src=\"\' + \\ + \"google-analytics.com\/ga.js\' type=\'text\/javascript\'%3E%3C\/script%3E\"开发者_StackOverflow社区));//g" myfile.html

Whats wrong here?


  1. Backslashes should be doubly escaped, since they are expanded by both sed and the shell. Use \\\\ (becomes \\ in the shell, then \ in sed)
  2. You're matching on src="', but your file contains src='".

Use

sed -i \
"s|document.write(unescape(\"%3Cscript src='\" + \\\\ + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));||g" \
myfile.html

I've replaced / with | to make it more readable (no more need to escape /).

0

精彩评论

暂无评论...
验证码 换一张
取 消