trying to find and replace a string using perl -
in perl, trying open file , find string, replace string, , close file. have scoured internet, , have come with:
#!/usr/bin/perl -w # use warnings; $oldurl = "somestring"; $newurl = "someotherstring"; $file = "somefile"; open (myfile,"$file") or die "can't open '$file': $!"; while(my $row = <myfile>){ if($row =~ /$oldurl/) { $row = "$newurl"; print myfile $row; } } close(myfile); this nothing except print screen text: somestring. cant newurl written in file, missing?
how files in dir end in .cfg:
#!/usr/bin/perl -w use warnings; $directory = '/tftpboot'; $oldurl = "account.1.sip_server_host = s150133.trixbox.fonality.com"; $newurl = "account.1.sip_server_host = 162.221.24.130"; .... .....
please read: perlfaq5 - how change, delete, or insert line in file, or append beginning of file?
i recommend using $inplace_edit handle opening , closing of file you. however, other methods listed in above reference:
#!/usr/bin/perl use strict; use warnings; use autodie; $file = "somefile"; $oldurl = "somestring"; $newurl = "someotherstring"; local @argv = $file; local $^i = '.bak'; while (<>) { s/.*$oldurl.*/$newurl/; # replacing whole line seems odd, it's did in example. print; } #unlink "$file$^i"; #optionally delete backup
Comments
Post a Comment