如何在命令行中使用Perl替换正则表达式多行dotall

时间:2019-03-19 15:51:09

标签: regex perl command-line

嗨,我是perl的新手,我想知道如何在多行模式下用它代替regex。并且如果可能的话也要使“。”与折线匹配。

我正在使用以下表达式:

perl -pe 's/text.*end/textChanged/g' myFile.txt

以上表达式在单行模式下替换。它不考虑折线。

使用: 视窗 Stranberry Perl

1 个答案:

答案 0 :(得分:3)

请注意,Perl单行代码使用-p或-n开关,这些开关在场景后包裹了while循环。 而且while循环使用逐行读取的标量上下文,因此除非text.*end出现在单行中,否则您将不会看到输出中的任何更改。

这是一个样本

$ cat  a.txt
abc
text 1 2
2 3 4
ab end
hello
here

$ perl -pe 's/text.*end/textChanged/g' a.txt # Nothing happens - while reads line by line
abc
text 1 2
2 3 4
ab end
hello
here

现在,您可以像将“记录分隔符”变量设置为undef

$ perl -pe ' BEGIN { $/=undef } s/text.*end/textChanged/g' a.txt # Nothing happens
abc
text 1 2
2 3 4
ab end
hello
here

但是,当您添加/ s修饰符时,替换就发生了。

$ perl -pe ' BEGIN { $/=undef } s/text.*end/textChanged/gs ' a.txt
abc
textChanged
hello
here
$

使用slurp模式读取整个文件,并且替换后仍然没有任何反应。

$ perl -0777 -pe ' s/text.*end/textChanged/g ' a.txt
abc
text 1 2
2 3 4
ab end
hello
here
$

现在,您使用/ s标志,以便点也可以与换行符匹配,并且替换将发生。

$ perl -0777 -pe ' s/text.*end/textChanged/gs ' a.txt
abc
textChanged
hello
here
$

感谢@ikegami ...的捆绑包选项,如下所示

$ perl -0777pe ' s/text.*end/textChanged/gs ' a.txt

因此,当您希望点与换行符匹配时,需要在正则表达式中添加/ s修饰符。