我需要在许多静态 html 文件中用新的通用跟踪代码替换旧的谷歌分析代码。旧代码如下所示:
_uacct = "UA-XXXXXX-X";
urchinTracker();
新代码如下:
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');ga('create', 'UA-XXXXXX-X', 'xxx.com');ga('require', 'displayfeatures');ga('send', 'pageview');
我正在尝试将 bash find 命令和 sed (CentOS 6) 结合起来:
find docs/ -type f -iname "*.html" -exec sed -i ':a;N;$!ba;s/_uacct = "UA-XXXXXX-X";\nurchinTracker();/(function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,\'script\',\'\/\/www.google-analytics.com\/analytics.js\',\'ga\');ga(\'create\', \'UA-XXXXXX-X\', \'xxx.com\');ga(\'require\', \'displayfeatures\');ga(\'send\', \'pageview\');/g' {} \;
但是,这会产生以下错误:
-bash: syntax error near unexpected token `('
经过一些研究,我发现括号也应该被转义:
find arts/ -type f -iname "bass.html" -exec sed -i ':a;N;$!ba;s/_uacct = "UA-XXXXXX-X";\nurchinTracker();/\(function\(i,s,o,g,r,a,m\){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function\(\){\(i[r].q=i[r].q||[]\).push\(arguments\)},i[r].l=1*new Date\(\);a=s.createElement\(o\),m=s.getElementsByTagName\(o\)[0];a.async=1;a.src=g;m.parentNode.insertBefore\(a,m\)}\)\(window,document,\'script\',\'\/\/www.google-analytics.com\/analytics.js\',\'ga\'\);ga\(\'create\', \'UA-XXXXXX-X\', \'xxx.com\'\);ga\(\'require\', \'displayfeatures\'\);ga\(\'send\', \'pageview\'\);/g' {} \;
>
>
正如您所看到的,bash 认为某些内容没有转义,因此断行并且不执行命令。
我做错了什么?
如果可以使用其他工具(比如说 awk)来做到这一点?
答案1
你无法转义单引号内的单引号。对您来说最简单的方法是将脚本放入文件中然后运行
find arts/ -type f -iname "bass.html" -exec sed -i -f your-script.sed '{}' \;
答案2
这对我有用
find docs/ -type f -iname "*.html" -exec \
perl -i.bak -0pe 's/_uacct = "UA-XXXXXX-X";\nurchinTracker\(\);/test/igs' {} \;
请注意,-i.bak
会生成带有扩展名的原始文件的副本.bak
,以防出现任何问题。现在替换的是 string test
。用你的长替代品替换它。
有了你的巨大替代品,它就会看起来像:
find docs/ -type f -iname "*.html" -exec perl -i.bak -0pe "s/_uacct = \"UA-XXXXXX-X\";\nurchinTracker\(\);/\(function\(i,s,o,g,r,a,m\)\{i\['GoogleAnalyticsObject'\]=r;i\[r\]=i\[r\]\|\|function\(\)\{\(i\[r\].q=i\[r\].q\|\|\[\]\).push\(arguments\)\},i\[r\].l=1\*new Date\(\);a=s.createElement\(o\),m=s.getElementsByTagName\(o\)\[0\];a.async=1;a.src=g;m.parentNode.insertBefore\(a,m\)\}\)\(window,document,'script','\/\/www.google-analytics.com\/analytics.js','ga'\);ga\('create', 'UA-XXXXXX-X', 'xxx.com'\);ga\('require', 'displayfeatures'\);ga\('send', 'pageview'\);/igs" {} \;