Perl replace text and save file

I have some scripts that has a password hard coded in them and need to make a script that I can replace them with.

Not sure how to do what I need to do, I can do it with a one line command to replace the word but I need to do this in a script and not sure how.

What I need to do is to run a small script where it will ask for a new password to enter then replace the password in the file, make a backup copy of the file then save the file.

So something to start with like:
------------------------------------------------
#!/usr/bin/perl
use strict;

my $file = "pass.pl";
my $Npass;

print "Enter a New Password: ";
my $Npass = <STDIN>; chomp $Npass;

$r = s/xxxyyy/$Npass/g;

------------------------------------------------

Example:

If is have a file named script1.pl and there is a line in it such as:

AdminPasswd:xxxyyy

Then I can modify the script1.pl to replace the xxxyyy with the new password given.

I'm just not sure how to open the file to edit then save it to a new copy from doing this in a script, on command line I can just do a perl -p -i -e 's/xxxyyy/NewPassWord/g'

Thanks,




bt707Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

zlobchoCommented:

#!/usr/bin/perl
use strict;
my $file=$ARGV[0];
#my $file = "pass.pl";
print "Enter a New Password: ";
my $Npass = <STDIN>;
chomp $Npass;
open (DATA,"$file") or die "can not open the inputfile\n";
while(<DATA>){
   open (FILE,">>new_$file") or die "can not create a new file\n";
   if ($_!~/AdminPasswd:(.*)/){
    print FILE $_;
   }
   if ($_=~/AdminPasswd:(.*)/){
       $_=~s/$1/$Npass/;
       print FILE $_;
       close (FILE);
   }
}
close (DATA);

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
bt707Author Commented:
zlobcho,

Thank you very much, that worked Great.

Thanks again!!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Perl

From novice to tech pro — start learning today.