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

Gabe Kopley picture Gabe Kopley · May 24, 2013 · Viewed 13.8k times · Source
$ 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

choroba picture choroba · May 24, 2013

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

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

-0777 sets the separator to undef, -0 alone sets it to \0 which might work for text files not containing the null byte.

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