如何在Perl中替换现有文件中的字符串? [英] How to replace a string in an existing file in Perl?
本文介绍了如何在Perl中替换现有文件中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在所有名为1_classification.dat,2_classification.dat等的文本文件中将单词"blue"替换为"red".我想编辑相同的文件,所以尝试了此代码,但是它不起作用.我要去哪里错了?
I want to replace word "blue" to "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 this 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屋!
查看全文