match string in file and replacement with other string

62 views Asked by At

I have a file containing lines as follows #comments abc #comments xyz SerialPort=100 Baudrate=9600 Parity=2 Databits=8 Stopbits=1

also I have array @in = ( SerialPort=500 , Baudrate=300, parity=0, Databits=16, Stopbits=0 ),these array elements read from browser, I am trying to write perl script to match "SerialPort" in file and replace SerialPort=100 in file with SerialPort=500 of array, I want match all other elments in loop I tried code not working please improve the code which is below, I think regular expression is not working and each time if condition to match and substitution resulting false, and also when I look at file after execution of script file consists of duplicates.

#!/usr/bin/perl
$old_file = "/home/work/conf";
open (fd_old, "<", $old_file) || die "cant open file";
@read_file = <fd_old>;
close (fd_old);
@temp = ();
$flag = 0;
foreach $infile ( @read_file )
{
    foreach $rr ( @in )
    {
        ($key, $value ) = split(/=/, $rr );

      if ( $infile =~ s/\b$key\b(.*)/$rr/ )
      {
          push ( @temp , $infile );
          $flag = 0;
       }
       else
        {
           $flag = 1;
        }
        }

        if ( $flag )
        {
                push (@temp, $infile );
        }

    }

    open ( fd, ">", $old_file ) || die "can't open";
    print fd @temp;
    close(fd);
2

There are 2 answers

4
Praveen On

@Maruti: Never write a perl program without use strict; and use warnings;. I have modified your code. Just have a look.

Code:

#!/usr/bin/perl
use strict;
use warnings;
my $old_file = "/home/work/conf";
open (my $fh, "<", $old_file) || die "cant open file";
my @read_file = <$fh>;
close ($fh);
my @temp = ();
my @in = ('SerialPort=500' , 'Baudrate=300', 'parity=0', 'Databits=16', 'Stopbits=0');
foreach my $infile ( @read_file )
  {
    foreach my $rr ( @in )
     {
       my ($key, $value) = split(/=/, $rr );
       if ( $infile =~ m/\b$key\b\=\d+/ && $infile =~ /#.*/)
         {
          $infile =~ s/\b$key\b\=\d+/$rr/ig;
             }  
         }  
      push (@temp, $infile );
     }
    open (my $out, ">", $old_file ) || die "can't open";
    foreach my $res(@temp)
     {
         print $out $res;
        }
    close($out);
0
Sobrique On

Perl 101: use strict; use warnings;.

Prefix variable names with $.

$old_file is undef when you try to open it.

And spell falg correctly, which if you'd turned on those options, you'd have been told about.

Also: When asking questions on SO, it's helpful if you point out what's not working.