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