目的是HEAD
在旧版HTML网站中的Google标记代码之后插入。
#!/bin/bash
find . -type f -iname "*.php" -or -iname "*.htm" -or -iname "*.html" | while read i; do
echo "Processing: $i"
sed -i 's*<HEAD>*&\
<!-- Global site tag (gtag.js) - Google Analytics -->\
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-1234567-2"></script>\
<script>\
window.dataLayer = window.dataLayer || [];\
function gtag(){dataLayer.push(arguments);}\
gtag('js', new Date());\
\
gtag('config', 'UA-1234567-2');\
</script>*' "$i"
done
上面将Google标记代码放在应有的位置,但没有单引号:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-1234567-2"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag(js, new Date());
gtag(config, UA-1234567-2);
处理后,单引号会丢失:
# diff actual_google_tag_code processed
6c6
< gtag('js', new Date());
---
> gtag(js, new Date());
8,9c8
< gtag('config', 'UA-1234567-2');
< </script>
---
> gtag(config, UA-1234567-2);
如果将替换'
为\'
,则会收到错误消息:
line 13: syntax error near unexpected token `('
line 13: ` gtag(\'js\', new Date());\'
由于我习惯于\
继续每一行,因此我不确定转义单引号的反斜杠是否可行,但是我想尝试一下。
如何在Google标记代码中保留这些单引号?
来自man 1 bash
:
将字符括在单引号中可保留引号内每个字符的字面值。即使在单引号之前加反斜杠,也不能在单引号之间引起单引号。
解决方案:将单引号放在双引号内:
gtag('"'js'"', new Date());\
# ^ - single quote was opened earlier, this character closes it
# ^^^^^^ - these are double quotes with content, single quotes are part of the content
# ^ - this single quote will be closed later
# Do not paste these comments into your script.
在任何需要的地方重复此技巧,它将像:
gtag('"'config', 'UA-1234567-2'"');\
(请记住,此行继续上一个已打开单引号的行;最后,它保持打开状态,以便在下一行关闭)。
通常,可以只'
用双引号引起来,而其他所有内容都用单引号引起,例如:
echo '$A'"'"'$B'"'"'$C'
# ^^ ^^ ^^ - in single quotes, so no variable expansion here
# ^ ^ - in double quotes, so ' is possible
结果是$A'$B'$C
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句