在perl中查找并替换文件中的字符串

时间:2014-11-11 10:11:23

标签: perl webmin-module-development

我正在尝试搜索文件中的字符串并将其替换为另一个字符串,我有像

这样的文件内容
 #comments abc
 #comments xyz
 SerialPort=100 #comment
 Baudrate=9600
 Parity=2
 Databits=8
 Stopbits=1

我希望将行SerialPort=100替换为SerialPort=500而不更改其他文件内容,并且不应更改SerialPort = 100旁边的注释,我已编写脚本但执行后所有注释行被删除了。帮助我这个和正则表达式上面的要求,这是我的代码

my $old_file = "/home/file";
my $new_file = "/home/temp";
open (fd_old, "<", $old_file ) || die "cant open file";
open (fd_new, ">", $new_file ) || die "cant open file";
while ( my $line = <fd_old> ) {
    if ( $line =~ /SerialPort=(\S+)/ ) {
        $line =~ s/SerialPort=(\S+)/SerialPort=$in{'SerialPort'}/;
        print fd_new $line;
    }
    else {
        print fd_new $line;
    }
}
close (fd_new);
close (fd_old);
rename ($new_file, $old_file) || die "can't rename file";

3 个答案:

答案 0 :(得分:1)

use strict;
my %in;
$in{SerialPort} = 500;
my $old_file = "file";
my $new_file = "temp";
open my $fd_old, "<", $old_file or die "can't open old file";
open my $fd_new, ">", $new_file or die "can't open new file";

while (<$fd_old>) {
    s/(?<=SerialPort=)\d+/$in{'SerialPort'}/;
    print $fd_new $_;
}

close ($fd_new);
close ($fd_old);
rename $new_file, $old_file or die "can't rename file";

答案 1 :(得分:1)

请考虑使用sed。它在这样的情况下表现出色:

sed -i 's/SerialPort=100/SerialPort=500/' /path/to/file

如果您需要编辑许多文件,请将sed与find和xargs配对:

find /path/to/directory -type f -name '*.ini' -print0 | xargs -0n16 sed -i 's/SerialPort=100/SerialPort=500/'

答案 2 :(得分:1)

perl -pe 's/findallofthese/makethemthis/g' input.txt > output.txt