Replace  text in a file

dfn48
dfn48 used Ask the Experts™
on
I wrote a program using Perl to find and replace a text within a file.

The text that needs to be replaced in the file is 'sql7.0.1' with 'sqls715'.


When I execute my program I get an error message:

can't /tmp/odbc.ini_old : A file or directory in the path name does not exist. I check the path and the path is correct. My OS is AIX.


Here is my code:


 
#!/usr/bin/perl

use strict;
use warnings;

my $filename = '/tmp/odbc.ini.2014_old';
my $find=' sql7.0.1 ';
my $replace = ' sqls715  ';

{
   local @ARGV =($filename);
   local $^I ='.bac';
   while (<>) {
     if (s/$find/$replace/ig) {
}
 else {
   print;
   }
 }
}
print "Finished"

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Is there any difference if you run this script?
#!/usr/bin/perl
use strict;
use warnings;

my $filename = '/tmp/odbc.ini.2014_old';
my $find=' sql7.0.1 ';
my $replace = ' sqls715  ';

open IN, $filename or die "could not open $filename: $!";
while (<IN>) {
    if (s/$find/$replace/ig) {
    }
    else {
        print;
    }
}
close IN;
print "Finished"

Open in new window

Author

Commented:
Thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial