Replacing Server Side Includes with a perl one-liner

Perl logo - black and white drawing of a camel.

I recently had to work on a site which had archives all the way back to 1997. In a few years’-worth of pages, they’d used Server Side Includes for things like a header and footer and navigation, and while there is nothing inherently wrong with that, we don’t support SSIs and recommend converting them to PHP includes. This would have meant converting thousands of html files to PHP, and also moving the archives from a files mount where PHP was not executable and including them in the code repository.

A standard search & replace is super easy, but in this case I wanted to replace several strings with the contents of several files. For each piece of include code there was a corresponding file, so I ran a command like this for each different one:

perl -pe 's/<!--#include virtual="..\/includes\/footer.html" -->/`cat ..\/includes\/footer.html`/ge' -i `find ./ -name "*.html"`

This loops (-p) through all the files in the directory the command is run from on the command line (e) and searches for<!--#include virtual="..\/includes\/footer.html" --> and, using cat, replaces it with the contents of the referenced html file only if find matches *.html.

The unescaped forward slashes are delimiters for the search and replace (s).

Leave a Reply

Your email address will not be published.

Pin It on Pinterest

Switch to mobile version