如何在 Perl 中替换现有文件中的字符串 [英] How to replace a string in an existing file in Perl
本文介绍了如何在 Perl 中替换现有文件中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想替换蓝色"这个词带有红色"在命名为 1_classification.dat、2_classification.dat 等的所有文本文件中.我想编辑同一个文件,所以我尝试了以下代码,但它不起作用.我哪里出错了?
I want to replace the word "blue" with "red" in all text files named as 1_classification.dat, 2_classification.dat and so on. I want to edit the same file so I tried the following code, but it does not work. Where am I going wrong?
@files = glob("*_classification.dat");
foreach my $file (@files)
{
open(IN,$file) or die $!;
<IN>;
while(<IN>)
{
$_ = '~s/blue/red/g';
print IN $file;
}
close(IN)
}
推荐答案
使用单行:
$ perl -pi.bak -e 's/blue/red/g' *_classification.dat
说明
-p
处理,然后逐行打印<>
-i
激活就地编辑.使用.bak
扩展名 备份文件- 正则表达式替换作用于隐式变量,即文件的内容,逐行
-p
processes, then prints<>
line by line-i
activates in-place editing. Files are backed up using the.bak
extension- The regex substitution acts on the implicit variable, which are the contents of the file, line-by-line
这篇关于如何在 Perl 中替换现有文件中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文