ovedpo15 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks!
I'm trying to write a one-liner filter with Perl. I want to catch everything between ABC and until XYZ. So I use:
/bin/cat $1 | perl -00 -pe 's/ABC(.*?)XYZ/\[DATA\]\n/s'
It works great but I want to also catch everything on the same line of XYZ. For example:
123 ABC 123 abc XYZ hi la
It will become:
123 [DATA] la
But with my regex it will be:
123 [DATA] hi la
How can I catch also 'hi'?

Replies are listed 'Best First'.
Re: Replacing between patterns
by haukex (Archbishop) on Oct 28, 2019 at 13:05 UTC
    I want to also catch everything on the same line of XYZ.

    You can say that explicitly: s/ABC(.*?)XYZ\N*\n/\[DATA\]\n/s will produce your desired output. (Note \N was added in 5.12, for older versions you can say e.g. [^\n].)

    Minor edits shortly after posting.

      Thanks! The old version is being supported on new versions as well?
        The old version is being supported on new versions as well?

        Yes, it is. Here's another backwards-compatible alternative: s/ABC(?s:.*?)XYZ.*/[DATA]/

Re: Replacing between patterns
by jwkrahn (Abbot) on Oct 28, 2019 at 20:34 UTC
    $ echo "123 ABC 123 abc XYZ hi la" | perl -0777pe 's/ABC(?s:.*?)XYZ.*/[DATA]/' 123 [DATA] la
      Similarly, but with /m and $:
      echo "123 ABC 123 abc XYZ hi la" | perl -0777 -pe 's/ ABC .*? XYZ .*? $ /[DATA]/msx' 123 [DATA] la