【问题标题】:Find and replace a string in file with another in Perl在 Perl 中查找文件中的字符串并将其替换为另一个字符串
【发布时间】:2014-11-11 10:11:22
【问题描述】:

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

#comments abc
#comments xyz
SerialPort=100 #comment
Baudrate=9600
Parity=2
Databits=8
Stopbits=1

我想用SerialPort=500 替换行SerialPort=100 而不更改文件的其他内容,并且不应更改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";

【问题讨论】:

  • 是否只删除了注释行(文件中的第 1 行和第 2 行)?
  • 是的,只有所有 cmets 被删除。
  • 它对我有用。您是否显示了您调用的确切脚本?不是有/^#/ and next之类的行吗?
  • @Maruti:您发布的脚本无法删除任何行...
  • 旁注; m// 后跟 s/// 是多余的,如果匹配成功,稍后也会返回。

标签: perl webmin-module-development


【解决方案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";

【讨论】:

  • 解释一下。
【解决方案2】:
perl -pe 's/findallofthese/makethemthis/g' input.txt > output.txt

【讨论】:

    【解决方案3】:

    考虑改用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/'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 2019-07-13
      • 2014-11-16
      • 2017-06-16
      • 2011-07-01
      • 2019-04-18
      • 1970-01-01
      相关资源
      最近更新 更多