我想搜索一個子字符串,並在找到子字符串時替換整個字符串。在下面的例子中,someVal可以是我不知道的任何值。perl搜索並替換一個子字符串
我如何搜索someServer.com並將$ oldUrl和$ newUrl替換爲整個字符串?
我能做到這一點對整個字符串就好了:
$directory = "/var/tftpboot";
my $oldUrl = "someVal.someServer.com";
my $newUrl = "someNewVal.someNewServer.com";
opendir(DIR, $directory) or die $!;
while (my $files = readdir(DIR)) {
next unless ($files =~ m/\.cfg$/);
open my $in, "<", "$directory/$files";
open my $out, ">", "$directory/temp.txt";
while (<$in>) {
s/.*$oldUrl.*/$newUrl/;
print $out $_;
}
rename "$directory/temp.txt", "$directory/$files";
}
替換中的'。*'使得整行匹配並被替換,並且我敢肯定你不想刪除整行。只匹配你想要替換的東西。 – TLP 2014-09-10 11:46:21