我有一堆文件,在页面底部有一些旧的谷歌跟踪代码:
<script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-XXXXXXXXX-1"); pageTracker._trackPageview(); } catch(err) {}</script>
我需要对其进行更新,使其具有新版本的 GA 代码:
<script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-xxxxxxx-1']); _gaq.push(['_setDomainName', 'site.com']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script>
通常我会使用 find 。 -name "*html"-exec sed s/find/replace/{}\;
来做到这一点,但据我所知,它无法处理多行。我如何修改这样的东西来查找和替换多行,我如何轻松处理我必须在命令行转义的所有东西?我不反对创建 bash 文件。
我也不反对将“查找”和“替换”内容放在文本文件中,然后以这种方式将其拉入命令 - 至少应该使转义部分更容易。
谢谢!
最佳答案
我会为此使用 perl。
像这样的事情应该让你开始:
#!/usr/bin/perl
use strict;
use warnings;
use File::Slurp qw/slurp/;
my $text = slurp($ARGV[0]);
$text =~ s/foo\nbar/new_and_shiny/;
my $newfile = $ARGV[0] . ".new";
open my $out, ">$newfile" or die "$!";
print $out $text;
close $out;
将 foo\nbar 替换为您的旧 javascript,并且不要忘记转义所有这些特殊字符 ()[] 等。
<编辑> Jim Garrison让我编辑这个答案并添加以下内容:
您可以更进一步,将文件中的所有 google analytics javascript 替换为单个占位符字符串,比如“GOOGLE_ANALYTIC_CODE”,看起来像这样:
<script>
GOOGLE_ANALYTIC_CODE
</script>
并对这些文件运行查找和替换脚本,用最新的 javascript 替换“GOOGLE_ANALYTIC_CODE”以创建“已部署”版本。
现在可能需要付出更多的努力,但肯定会让你 future 的自己受益。
这种做法在 The Pragmatic Programmer 中有很好的记录。当他们讨论“DRY 原则”(Dont-Repeat-Yourself) 时预订。
我怎么推荐那本书都不为过。那里有很多很多好的建议。
编辑>
关于linux - 如何从 *Unix 命令行进行多行查找和替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5508245/