954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Search and Replace Script

0
By KevinADC on Jan 16th, 2007 12:03 pm

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";

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

floridamason
Newbie Poster
1 post since Nov 2009
Reputation Points: 10
Solved Threads: 0
 

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

roswell1329
Junior Poster in Training
71 posts since May 2006
Reputation Points: 21
Solved Threads: 2
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You