如何使用Perl在多行中搜索和替换? [英] How do I search and replace across multiple lines with Perl?

查看:110
本文介绍了如何使用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?

推荐答案

您可以使用-0开关更改输入分隔符:

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

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

-0777将分隔符设置为undef,单独将-0设置为\0,这可能适用于不包含空字节的文本文件.

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

请注意,由于正则表达式既不包含^也不包含$,因此/m是不必要的.

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

这篇关于如何使用Perl在多行中搜索和替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆