Trent Three Trent Three - 1 year ago 108
Perl Question

Perl command line to replace text block across multi-line using regex

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 -->


<?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


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.


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.