简体   繁体   English

用sed替换文本文件中带引号和双引号的字符串

[英]Replacing string in textfile with quotes and doublequotes with sed

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命令,但令人惊讶的是根本没有任何反应。

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

Whats wrong here? 怎么了

  1. Backslashes should be doubly escaped, since they are expanded by both sed and the shell. 反斜杠应加倍转义,因为它们由sed和shell扩展。 Use \\\\\\\\ (becomes \\\\ in the shell, then \\ in sed ) 使用\\\\\\\\ (成为\\\\的壳,然后\\sed
  2. You're matching on src="' , but your file contains src='" . 您在src="'上进行匹配,但是您的文件包含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 / ). 使其更具可读性(不再需要转义/ )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM