1

I've got a bunch of html files that I need to replace the following text:

<div id="header">
plus all info between
<!-- end #header -->

with

<?php include ("header.php"); ?>

I thought I could run something like this but it isn't matching the text:

perl -p -i.bak -e 's/<div id="header">.*<!\-\- end #header \-\->/<\?php include \("header\.php"\); \?>/g' *.html

or

perl -p -i.bak -e 's/<div id="header">[\S\s\n]*<!\-\- end \#header \-\->/<\?php include \("header\.php"\); \?>/img' *.html

I don't know if it's not searching across multiple lines and I need a parameter or I'm not escaping characters right. Any help would be appreciated.

I would like to batch run this in a directory and change all the content within each file where appropriate.

EDIT: looking for a single command line version, not using multiple pl files if possible.

Trent Three
  • 211
  • 2
  • 10
  • Possible duplicate [How to replace multiple any-character (including newline) in Perl RegEx?](http://stackoverflow.com/questions/36533282/how-to-replace-multiple-any-character-including-newline-in-perl-regex/36534283#36534283) – Håkon Hægland May 29 '16 at 18:53
  • Not a duplicate, but that explains why it's not working (-p option is the culprit?) but I don't understand what the structure should be of the search-and-replace code in the example. It would be helpful if we could have an actual working copy of the example above. – Trent Three May 29 '16 at 19:05
  • Is there perhaps an alternative to the -p command to read the file as one line? And how would the SnR code be integrated? Ideally I'm thinking this can be coded as a single command line without having to create a separate perl file? – Trent Three May 29 '16 at 19:06

1 Answers1

2

You can set the record separator with the -0 option. Like so:

perl -0pe 's/.../.../g' *.html

This sets the record separator to the NUL character, so that the entire file is read at once, rather than line by line.

Hellmar Becker
  • 2,824
  • 12
  • 18
  • This should work, but one day a file will come along that contains a legitimate NUL character and your command will break. It's best to use `perl -0777 -pe ' ... '` which sets `$/` to `undef` – Borodin May 30 '16 at 09:23