我有几个网站,每个网站都有多个页面。每个页面都有多个脚本用于各种功能。我试图在所有网站上注释掉一个特定的脚本。
我想要注释掉的脚本有一个目标词,我可以将其用作条件将其与其余部分隔离。我想使用该词来定位脚本并将其全部内容(大约 10 行/包括 <script>
标签本身)包含在注释中。
我考虑过使用正则表达式,但似乎脚本语法的多行和复杂性质可能会使这种情况超出正则表达式解决方案的范围。我不熟悉正则表达式,所以我可能是错的。
这里是需要注释掉的内容的粗略想法。我想保留的是其他类似的没有条件词的脚本 block (在本例中为“oranges.com”):
<script type='text/javascript'>
window.__wtw_lucky_site_id = 15001;
(function() {
var wa = document.createElement('script'); wa.type = 'text/javascript'; wa.async = true;
wa.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://ww7632') + '.oranges.com/w.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wa, s);
})();
</script>
我想还值得一提的是,我将通过 ssh 访问和操作这些文件,因此最好该解决方案能够以某种方式与之兼容。
最佳答案
您可以使用 Perl 来完成此操作(您要注释的脚本中包含 stuff
):
$ cat test.xml
<html>
<script>
stuff
</script>
<script>
other things
</script>
<body>
<h1>Hello, world!</h1>
</body>
</html>
$ perl -0pe 's/<script([^>]*>.*?stuff.*?)<\/script>/<!-- script\1<\/script -->/smg' test.xml
<html>
<!-- script>
stuff
</script -->
<script>
other things
</script>
<body>
<h1>Hello, world!</h1>
</body>
</html>
有关引用,请参阅here 。这是一个非常快速且肮脏的解决方案。您还可以编写一个脚本来使用任意数量的库来解析 XML、循环元素并修改 XML。
可能有一种 XSLT 方法,但我找不到一种看起来特别直接的方法。
关于html - 跨多个网站有条件地注释 html 脚本语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27746742/