用 perl 替换两个字符串之间的所有文本,包括换行符
Replace all text, including newlines, between two strings with perl
我有数百个遵循特定格式的自述文件。我需要用不同的内容替换每个文本中的一大块文本。一切都很好,除了如果单词之间有换行符 \n
,我无法 select 单词。举例如下:
...
this
is
old
content
...
我想替换这些文件中的所有文本,使它们看起来像这样
...
new content
...
我尝试了以下 perl 命令,但它们对换行符不起作用
perl -pi -w -e 's/this(\n|.)*?content/new content/g;' *.txt
我已经尝试根据 添加 /s 标签(也许我做错了..)
perl -pi -w -e 's/this(\n|.)*?content/new content/gs;' *.txt
没有“?”
perl -pi -w -e 's/this(\n|.)*content/new content/g;' *.txt
使用 (.+?) 而不是 (\n|.) 基于 Regex to match any character including new lines
perl -pi -w -e 's/this(.+?)*content/new content/g;' *.txt
使用 [\s\S] 而不是 (\n|.) 基于 Regex to match any character including new lines
perl -pi -w -e 's/this[\s\S]*content/new content/g;' *.txt
我在 regexpal.com 中尝试了这些表达式,据说它们工作得很好。
如果我从自述文件中删除换行符,所有这些示例 perl 命令的 all 都可以正常工作。我做错了什么?
您想添加 0777
。所以你的一个班轮应该是。
perl -0777 -pi -e 's/this.*?content/new content/sg;' *.txt
0777
是一种 slurp 模式。它将整个文件传递给 $_
中的脚本
这等于local $/;
open my $fh,"<","file";
local $/;
my $s = <$fh>;
此处整个文件将存储到$s
。
那么,不需要在你的模式中添加 \n
。因为 s
修饰符允许 .
匹配任何字符,包括换行符。
我有数百个遵循特定格式的自述文件。我需要用不同的内容替换每个文本中的一大块文本。一切都很好,除了如果单词之间有换行符 \n
,我无法 select 单词。举例如下:
...
this
is
old
content
...
我想替换这些文件中的所有文本,使它们看起来像这样
...
new content
...
我尝试了以下 perl 命令,但它们对换行符不起作用
perl -pi -w -e 's/this(\n|.)*?content/new content/g;' *.txt
我已经尝试根据 添加 /s 标签(也许我做错了..)
perl -pi -w -e 's/this(\n|.)*?content/new content/gs;' *.txt
没有“?”
perl -pi -w -e 's/this(\n|.)*content/new content/g;' *.txt
使用 (.+?) 而不是 (\n|.) 基于 Regex to match any character including new lines
perl -pi -w -e 's/this(.+?)*content/new content/g;' *.txt
使用 [\s\S] 而不是 (\n|.) 基于 Regex to match any character including new lines
perl -pi -w -e 's/this[\s\S]*content/new content/g;' *.txt
我在 regexpal.com 中尝试了这些表达式,据说它们工作得很好。
如果我从自述文件中删除换行符,所有这些示例 perl 命令的 all 都可以正常工作。我做错了什么?
您想添加 0777
。所以你的一个班轮应该是。
perl -0777 -pi -e 's/this.*?content/new content/sg;' *.txt
0777
是一种 slurp 模式。它将整个文件传递给 $_
这等于local $/;
open my $fh,"<","file";
local $/;
my $s = <$fh>;
此处整个文件将存储到$s
。
那么,不需要在你的模式中添加 \n
。因为 s
修饰符允许 .
匹配任何字符,包括换行符。