Find and replace a string in file with another in Perl

282 views Asked by At

I am trying to search a string in file and replace that with another string. I have file content like

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

I want to replace line SerialPort=100 with SerialPort=500 without altering other content of the file and also the comment next to SerialPort=100 should not be altered.

I have written a script, but after execution all comment lines are getting deleted. How can I do this with a regular expression for above requirement?

Here is my code

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

There are 3 answers

1
nowox On
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";
0
diz On

Consider using sed instead. It excels in situations like this:

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

If you have many files you need to edit, pair sed with find and xargs:

find /path/to/directory -type f -name '*.ini' -print0 | xargs -0n16 sed -i 's/SerialPort=100/SerialPort=500/'
0
tkjef On
perl -pe 's/findallofthese/makethemthis/g' input.txt > output.txt