Alexander Alexander - 5 months ago 6
Perl Question

Replace a string in file

My file is like this

DIV=25
FACILITY=11111


and I want to use Perl to replace DIV=25 into DIV=30. Below is my script to do it, but the output of the file is DIV=3030

open( IN_IOE, $FILE_NAME ) || die "Cannot open file";
my @line_ioe = <IN_IOE>;
close(IN_IOE);
chomp @line_ioe;

foreach $_ ( @line_ioe ) {
s/DIV=/DIV=30/
}

open( OUT, ">test.txt" );
foreach $_ (@line_ioe) {
print OUT "$_ \n";
}
close(OUT);


The output of my file is

DIV=3030
FACILITY=11111


Can anyone please show me how to replace that line in file with Perl, and point out where I was wrong.

Answer

if you have multiple lines with different numeric numbers (i.e. DIV=25, DIV =31, DIV=21) you could do following.

s/DIV=\d/DIV=25/g

here \d is to replace any digits and 'g' to perform this globally.

Comments