尝试使用perl查找和替换字符串

时间:2014-08-18 21:08:25

标签: perl

在perl中,我试图打开一个文件,找到一个字符串,替换该字符串,然后关闭该文件。我已经浏览了互联网,这就是我想出的:

  #!/usr/bin/perl -w
  #  use warnings;  

    my $oldUrl = "someString";
    my $newUrl = "someOtherString";
    $file = "someFile";
    open (MYFILE,"$file") or die "Can't open '$file': $!";
    while(my $row = <MYFILE>){
            if($row =~ /$oldUrl/)
            {
                    $row = "$newUrl";
                    print MYFILE $row;
            }
    }
    close(MYFILE);

除了打印屏幕文本之外什么都不做:someString。我不能让newUrl实际写入文件中,我缺少什么?

我将如何处理以.cfg结尾的目录中的所有文件:

  #!/usr/bin/perl -w
use warnings;

my $directory = '/tftpboot';

my $oldUrl = "account.1.sip_server_host = s150133.trixbox.fonality.com";
my $newUrl = "account.1.sip_server_host = 162.221.24.130";
 ....
  .....

2 个答案:

答案 0 :(得分:3)

请阅读:perlfaq5 - How do I change, delete, or insert a line in a file, or append to the beginning of a file?

我建议使用$INPLACE_EDIT来处理文件的打开和关闭。但是,上述参考文献中列出了其他方法:

#!/usr/bin/perl
use strict;
use warnings;
use autodie;

my $file = "someFile";
my $oldUrl = "someString";
my $newUrl = "someOtherString";

local @ARGV = $file;
local $^I = '.bak';
while (<>) {
    s/.*$oldUrl.*/$newUrl/;   # Replacing the whole line seems odd, but it's what you did in your example.
    print;
}
#unlink "$file$^I"; #Optionally delete backup

答案 1 :(得分:1)

您可以使用此单行代码替换文件中的字符串:

perl -pi.bak -e 's/someString/someOtherString/g' someFile