1

I am trying to insert a piece of JavaScript before the closing <\body> tag of over 2000 HTML files. This is what I have tried. But it does not do the job.

perl -pi -w -e 's/\<\/body\>/\<div id=\"fb-root\"\>\<\/div\>
    \<script type=\"text\/javascript\" src=\"https:\/\/connect.facebook.net\/en_US\/all.js\"\>\<\/script\> 
    \<script type=\"text\/javascript\"\>

    FB.init\(\{
        appId: \"446059218762070\", 
        status: true, 
        cookie: true, 
        xfbml: true
    });

    \/\* As of Jan 2012 you need to use \*\/
    FB.Canvas.setAutoGrow\(2\);
    \<\/script\>
\<\/body\>/g' *.html

I have done some other replacement scripts with perl -pi, that worked well like

perl -pi -w -e 's/\<a href=\"index.html\"\>/\<a class=\"top_button\" href=\"index.html\"\>/g' *.html

and

perl -pi -w -e 's/\<link rel=\"STYLESHEET\" type=\"text\/css\" href=\"default.css\"\>/\<link rel=\"STYLESHEET\" type=\"text\/css\" href=\"default.css\"\>
\<script type=\"text\/javascript\" src=\"https:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1.4\/jquery.min.js\"\>\<\/script\>
\<script type=\"text\/javascript\" src=\"default.js\"\>\<\/script\>/g' *.html

Can anyone help me? what is wrong with my one-liner Perl script?

4

2 回答 2

3

主要问题是您正在尝试进行多行搜索和替换,但正在逐行处理文件。以下修改过的单线应该可以工作:

perl -i -wpe 'BEGIN{undef $/;} s[<div id="fb-root".+?</body>][</body>]gs' *.html

请注意,我已经简化了您的搜索字符串。没有必要逐个字符地重复整个 HTML/JavaScript 序列。还有几个元字符应该在搜索字符串中转义。

于 2012-07-12T00:43:42.670 回答
2

我不明白它为什么会失败,但你不必要地逃避了太多的字符,以至于任何错误都变得不可见。

您没有在模式或替换字符串中使用方括号,所以我建议您使用它们来分隔替换,像这样

perl -i -wpe 's[</body>][<div id="fb-root"></div>
    <script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"></script> 
    <script type="text/javascript">

    FB.init({
        appId: "446059218762070", 
        status: true, 
        cookie: true, 
        xfbml: true
    });

    /* As of Jan 2012 you need to use */
    FB.Canvas.setAutoGrow(2);
    </script>
</body>]g' *.html

只是在黑暗中拍摄:我想知道</body>您文件中的标签是否为大写?在这种情况下,您的比赛将失败。我建议您添加i修饰符 (making gi) 以确保。

于 2012-07-11T18:02:22.137 回答