简体   繁体   中英

Replace JavaScript code of HTML files with Perl

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?

The main problem is that you are trying to do a multi-line search and replace but are processing the files line by line. The following modified one-liner should work:

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

Note that I have simplified your search string. It's not necessary to repeat the whole HTML/JavaScript sequence character by character. There were also several meta-characters that should have been escaped in the search string.

I can't see why it would fail, but you are unnecessarily escaping far too many characters so that any mistakes become invisible.

You aren't using square brackets in the pattern or the replacement string, so I suggest you use them to delimit the substitution, like this

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

Just one shot in the dark: I wonder if the </body> tag in your files is in upper case? In that case your match would fail. I suggest you add the i modifier (making gi ) just to make sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM