Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Perl中查找并用另一个字符串替换文件中的字符串_Perl_Webmin Module Development - Fatal编程技术网

在Perl中查找并用另一个字符串替换文件中的字符串

在Perl中查找并用另一个字符串替换文件中的字符串,perl,webmin-module-development,Perl,Webmin Module Development,我试图在文件中搜索一个字符串,并用另一个字符串替换它。我有像这样的文件内容 #评论abc #评论xyz SerialPort=100#注释 波特率=9600 奇偶校验=2 数据位=8 停止位=1 我想用SerialPort=500替换行SerialPort=100,而不改变文件的其他内容,而且SerialPort=100旁边的注释也不应该被改变 我已经写了一个脚本,但是在执行之后所有的注释行都被删除了。如何使用正则表达式来满足上述要求 这是我的密码 my $old_file = "/

我试图在文件中搜索一个字符串,并用另一个字符串替换它。我有像这样的文件内容

#评论abc
#评论xyz
SerialPort=100#注释
波特率=9600
奇偶校验=2
数据位=8
停止位=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";
my$old_file=“/home/file”;
my$new_file=“/home/temp”;
打开(fd_旧,“,$new_文件)| |模具“无法打开文件”;
while(我的$line=){
如果($line=~/SerialPort=(\S+/){
$line=~s/SerialPort=(\s+)/SerialPort=$in{'SerialPort'}/;
打印fd_新的$行;
}
否则{
打印fd_新的$行;
}
}
关闭(fd_new);
关闭(fd_old);
重命名($new_file,$old_file)| |死“不能重命名文件”;
严格使用;
我的%in;
{SerialPort}中的$500;
我的$old_file=“file”;
我的$new_file=“temp”;
打开我的$fd_old,“考虑改用它。它在以下情况下表现出色:

sed -i 's/SerialPort=100/SerialPort=500/' /path/to/file
如果有许多文件需要编辑,请与和配对:


仅删除注释行(文件中的第1行和第2行)是的,只有所有的评论都被删除了。这对我有用。你显示了你调用的确切脚本了吗?难道没有像
/^#/和next
或类似的行吗?@Maruti:你发布的脚本不能删除任何行……侧注;
m/
后跟
s/
是多余的,因为如果匹配成功,后面还会返回。一个解释是一切都井然有序。
sed -i 's/SerialPort=100/SerialPort=500/' /path/to/file
find /path/to/directory -type f -name '*.ini' -print0 | xargs -0n16 sed -i 's/SerialPort=100/SerialPort=500/'
perl -pe 's/findallofthese/makethemthis/g' input.txt > output.txt