我是计算机爱好者但从未学过编程。
我正在尝试学习Perl,因为我发现它很有趣,因为我学会了使用Perl风格的一些正则表达式,因为我需要替换字符串的某些部分中的单词,这就是我的方式发现perl。
但我对编程一无所知,我想知道如何使用shell(终端)或基本脚本中的正则表达式的简单示例。
例如,如果我在文件夹中有一个名为:input.txt的文本文档 我该如何执行以下正则表达式。
要匹配的文字:
text text text
text text text
我想要的是:更改第二次出现的单词text:changed
(\A.*?tex.*?)text(.*?)$
替换为:\1changed\3
预期结果:
text changed text
text changed text
使用将使用多行和全局修改器的文本编辑器。 现在,我如何从shell处理它。 CD路径然后呢? 还是一个脚本?应该包含哪些内容才能使其可行。
请考虑我对Perl一无所知,但只考虑其正则表达式语法
答案 0 :(得分:3)
正则表达式部分很简单。
s/\btext\b.*?\K\btext\b/changed/;
然而,如果你正在学习perl,如何应用它...这是困难的部分。人们可以证明一个班轮,但这没有用。
perl -i -pe 's/\btext\b.*?\K\btext\b/changed/;' file.txt
相反,我建议您查看perlfaq5 #How do I change, delete, or insert a line in a file, or append to the beginning of a file?
。最后,您需要学习的是如何打开文件进行阅读,并迭代。或者,如何打开文件进行写作。使用这两个工具,您可以做很多事情。
use strict;
use warnings;
use autodie;
my $file = 'blah.txt';
my $newfile = 'new_blah.txt';
open my $infh, '<', $file;
open my $outfh, '>', $newfile;
while (my $line = <$infh>) {
# Any manipulation to $line here, such as that regex:
# $line =~ s/\btext\b.*?\K\btext\b/changed/;
print $outfh $line;
}
close $infh;
close $outfh;
更新以解释正则表达式
s{
\btext\b # Find the first 'text' not embedded in another word
.*? # Non-greedily skip characters
\K # Keep the stuff left of the \K, don't include it in replacement
\btext\b # Match 2nd 'text' not embedded in another word
}{changed}x; # Replace with 'changed' /x modifier to allow whitespace in LHS.