replace
# replace
#!/usr/bin/perl
my @data = ();
my ($fname ,$rp, $nfname)= @ARGV;
my ($o, $n) = split("/", $rp);
open(of, "<$fname") or die "$fname 文件打开失败!$!";
while(<of>){
chomp;
$_ =~ s/$o/$n/;
push @data, "$_\n";
}
if(@data != 0) {
chomp @data; # 砍掉最后的 \n
open(nf_handle, ">$nfname") or die "Error: 文件$nfname打开失败$!";
print nf_handle @data;
}
执行
perl replace text.txt world/ajanuw ajanuw.txt
text.txt
hello world
world asd
123world456
231
ajanuw.txt
hello ajanuw
ajanuw asd
123ajanuw456
231
改变源文件
# replace
#!/usr/bin/perl
my @data = ();
my ($fname ,$rp)= @ARGV;
my ($o, $n) = split("/", $rp);
open(rf, "<$fname") or die "$fname 文件打开失败! $!";
while(<rf>){
chomp;
$_ =~ s/$o/$n/;
push @data, "$_\n";
}
if(@data != 0) {
chomp @data; # 砍掉最后的 \n
open(wf, "+>$fname") or die "$!";
print wf @data;
}