{"id":2230,"date":"2008-09-23T07:26:00","date_gmt":"2008-09-23T07:26:00","guid":{"rendered":"http:\/\/t.motd.kr\/articles\/2230\/inserting-google-analytics-tracking-code-using-shell-script"},"modified":"2022-12-28T01:45:33","modified_gmt":"2022-12-27T16:45:33","slug":"inserting-google-analytics-tracking-code-using-shell-script","status":"publish","type":"post","link":"https:\/\/vault.motd.kr\/wordpress\/posts\/2230\/inserting-google-analytics-tracking-code-using-shell-script\/","title":{"rendered":"Inserting Google Analytics Tracking Code using Shell Script"},"content":{"rendered":"\n
In most cases, you should be able to configure your CMS<\/span> or blog template to insert the Google Analytics<\/a> JavaScript tracking code at the end of every page in your web site.<\/p>\n\n\n\n However, you sometimes need to install the tracker code into static HTML<\/span> pages which are not managed by the CMS<\/span>, If you have a LOT<\/span> of static HTML<\/span> pages, then your fingers are in trouble.<\/p>\n\n\n\n Here\u2019s the Bash shell script which inserts the Google Analytics tracker code into all static HTML<\/span> pages. Please modify it before you run it, to meet your needs. Never forget to backup the original copy \u2014 it might work incorrectly for you:<\/p>\n\n\n\n In most cases, you should be able to configure your CMS or blog template to insert the Google Analytics JavaScript tracking code at the end of every page in your web site. However, you sometimes need to install the tracker code into static HTML pages which are not managed by the CMS, If you have… Continue reading #!\/bin\/bash\n# inject-google-analytics\nTRACKER_ID=\"UA-XXXXX-X\"\nTRACKER_CODE=\"<script type=\\\"text\/javascript\\\">\nvar gaJsHost = ((\\\"https:\\\" == document.location.protocol) ? \\\"https:\/\/ssl.\\\" : \\\"http:\/\/www.\\\");\ndocument.write(unescape(\\\"%3Cscript src='\\\" + gaJsHost + \\\"google-analytics.com\/ga.js' type='text\/javascript'%3E%3C\/script%3E\\\"));\n<\/script>\n<script type=\\\"text\/javascript\\\">\ntry {\nvar pageTracker = _gat._getTracker('$TRACKER_ID');\npageTracker._trackPageview();\n} catch(err) {}<\/script>\"\n\nfind . -name '*.html.new' -delete\nfind . '(' -name '*.html' -and -not -name '*-frame.html' ')' | while read -r TARGET; do\n if grep -qiP \"(<frameset|$TRACKER_ID)\" \"$TARGET\"; then\n continue;\n fi\n\n if grep -qiF '<\/body>' \"$TARGET\"; then\n perl -pi -e \"s\/(<\\\/body>)\/\\n${TRACKER_CODE\/\/\/\/\\\/}\\n$1\/i\" < \"$TARGET\" > \"$TARGET.new\"\n else\n { cat \"$TARGET\"; echo; echo \"$TRACKER_CODE\"; echo; } > \"$TARGET.new\"\n fi\n if ! grep -qF \"$TRACKER_ID\" \"$TARGET.new\"; then\n echo \"Failed to inject analytics script: $TARGET\"\n cat \"$TARGET.new\"\n rm -f \"$TARGET.new\"\n exit 1\n fi\n mv -f \"$TARGET.new\" \"$TARGET\"\ndone<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"