Search and Replace Script

KevinADC 0 Tallied Votes 232 Views Share

This is a bare-bones search and replace script that uses perls in-place editor and the File::Find module to get the job done quickly. It will search in all sub directories of the start directory and find and replace the text you specify in the type of file you specify. Keep in mind, this is a bare-bones implementation that is more for learning than for pratical use. It could be altered to accept command line arguments, input from the keyboard, or run as a CGI. That is up to you to figure out. :cheesy:

#!/usr/bin/perl 

use strict; 
use warnings; 
use File::Find; 

my $startdir = '/path/to/start/dir'; 
my $find = 'this'; 
my $replace = 'that'; 
my $doctype = 'txt';  

print qq~Finding "$find" and replacing it with "$replace"\n~; 

find( 
   sub{ 
      return unless (/\.$doctype$/i); 
      local @ARGV = $_; 
      local $^I = '.bac'; 
      while( <> ){ 
         if( s/$find/$replace/ig ) { 
            print; 
         } 
         else { 
            print; 
         } 
      } 
}, $startdir);

print "Finished";
floridamason 0 Newbie Poster

Super Nube,

I want to create a script that will pull a config off of a Cisco IPS (tftp probably) and once it is on the TFTP directory, change the IP Address for the sensor, the host name for the sensor and then TFTP it to the secondary IPS sensor. The IPSs are supposed to be running in HA, but Cisco does not have (or I do not know of it) a way to sync the two configs. I used the code I got from this post, but I was not sure how to add addition FIND and REPLACE.

Thanks


#!/usr/bin/perl

use strict;
use warnings;
use File::Find;

my $startdir = 'c:\ips-test';
my $find = 'host-ip 5\.3\.220\.101';
my $replace = 'host-ip 5.3.220.102';
my $doctype = 'txt';

print qq~Finding

roswell1329 11 Junior Poster in Training

You could do this with the no-script chain-saw approach:

perl -pi.bak -e 's/host\-ip 5\\\.3\\\.220\\\.101/host\-ip 5\.3\.220\.102;' c:\ips-test\*.txt

:D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.