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

我是研究僧i 提交于 2019-11-27 12:49:53

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 $.

It has to do with the -p switch. It reads input one line at a time. So you cannot run a regexp against a newline between two lines because it will never match. One thing you can do is to read all input modifying variable $/ and apply the regexp to it. One way:

perl -e 'undef $/; $s = <>; $s =~ s/foo\nbar/FOO\nBAR/; print $s' baz.txt

It yields:

FOO
BAR
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!