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.

3
  • Possible duplicate How to replace multiple any-character (including newline) in Perl RegEx? Commented May 29, 2016 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. Commented May 29, 2016 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? Commented May 29, 2016 at 19:06

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.