【发布时间】: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