2

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

#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";
4

3 回答 3

1

考虑改用sed。它在以下情况下表现出色:

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

如果您有许多文件需要编辑,请将 sed 与findxargs配对:

find /path/to/directory -type f -name '*.ini' -print0 | xargs -0n16 sed -i 's/SerialPort=100/SerialPort=500/'
于 2014-11-15T04:01:06.687 回答
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";
于 2014-11-11T13:18:19.557 回答
1
perl -pe 's/findallofthese/makethemthis/g' input.txt > output.txt
于 2016-01-19T07:27:08.460 回答