html - 跨多个网站有条件地注释 html 脚本语句

标签 html regex bash scripting conditional-statements

我有几个网站,每个网站都有多个页面。每个页面都有多个脚本用于各种功能。我试图在所有网站上注释掉一个特定的脚本。

我想要注释掉的脚本有一个目标词,我可以将其用作条件将其与其余部分隔离。我想使用该词来定位脚本并将其全部内容(大约 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/

相关文章:

java - 从 matcher.replaceAll() 获取 $1 的值

c++ - 有没有办法从 pcrecpp 获取 PREMATCH ( $`) and POSTMATCH ($' )?

linux - shell 脚本 : value too great for base (error token is "16#?")

javascript - HTML5 Canvas 上的矩形被拉伸(stretch)

javascript - 将 javascript 生成的框架转换为 div

regex - 我可以使用 tidyr 中的 separator() 或 extract() 将可变长度的数值拆分为其组成数字吗?

Bash 在命令行上工作,但不在 perl 脚本中工作

bash - 如何删除数组中的元素,然后在 Shell 脚本中移动数组?

javascript - 无法将数组或对象设置为 html5 Web 存储?

javascript - 在 Javascript 中动态创建和附加制表符空间