Gabe Kopley Gabe Kopley - 3 months ago 10
Perl Question

How do I search and replace across multiple lines with Perl?

$ perl --version
This is perl, v5.10.1 (*) built for x86_64-linux-gnu-thread-multi

$ echo -e "foo\nbar" > baz.txt
$ perl -p -e 's/foo\nbar/FOO\nBAR/m' baz.txt
foo
bar


How can I get this replacement to work?

Answer

You can use the -0 switch to change the input separator:

perl -0pe 's/foo\nbar/FOO\nBAR/' baz.txt

Note that /m is needless as the regex does not contain ^ nor $.