historystamp historystamp - 3 months ago 12
Perl Question

Command line s span multiple lines in Perl

This is my one-line Perl command in a Bash script. How do I get the s to change across multiple lines?

#!/bin/bash

file=$1
echo "processing $file"
perl -0777pe 's/.*<script[ |>].*<\/script>/<script> \.\.\. <\/script>/g' "$file" >"${file}changed.txt"


I am inputting an XHTML file in this script. The Perl command line works fine when begin script and end script tags are in the same line. Perl does not find the begin script and end script tags when on separate lines.

Is there a problem with <> in a regular expression?

Answer

Try this:

perl -0777pe 's:<script[ |>].*?</script>:<script> ... </script>:gs' "$file"

From the prelre:

s

Treat string as single line. That is, change "." to match any character whatsoever, even a newline, which normally it would not match.

The non-greed match .*? help with multiple <script> </script> blocks. Without it, (so greed match .*) for the

<script> some </script> <script> some2 </script>

will give only one

<script>...</script>

With the non-greed match (.*?) the for the same input will give

<script>...</script> <script>...</script>
Comments