Tips Tricks Tutorials

WEB-NES-BAY

Learn Tips and tricks on Linux, Hacking, linux, PHP, Perl, Web, Hardware

bookmark bookmark
WEBNESBAY On June - 27 - 2009

This is a script I use whenever I need to do search and replace in a bunch of files. It was meant as a quick hack, but since I does exactly what I need, I continue to use it (always make a backup of the original files in case something goes wrong).

 #!/usr/bin/perl -w
 #
 # More scripts and tips can be found at
 # http://www.edlin.org/
 #
 # Search and replace in several files
 #
 # I throw this file in my ~/bin/
 # Edit the variables $search, $replace and perhaps you want to change the globbing
 # then I jump to the directory with the files and just execute msr.pl (make sure that ~/bin is in your $PATH)

 use strict;

 my @infiles = glob("*.html");

 my $search ='dilbert';
 my $replace ='wally';

 # Here we go.........

 foreach my $file (@infiles){
   print "Processing $file\n";
   open(FH,$file) || die "Cannot load $file";
   my @lines=<FH>;
   close(FH);
   my $match=0;
   foreach my $line (@lines){
     if($line =~ s/$search/$replace/g){
       $match=1;
     }
   }

   if($match){
     print "...Saving $file\n";
     open(FS,">$file") || die "Cannot save $file";
     print FS @lines;
     close(FS);
   }
 }

output

when hacking some scripts it is useful to use $0 when printing out stuff, that way you can figure out which scripts that generate the output if you end up having scripts that use others scripts etc.

 print "$0: Some output from script $0\n";

Related posts:

  1. search & replace in several files in perl script
  2. Special shortcuts in Perl
  3. Create PDF using perl
  4. Run IMAP with PERL
  5. Generating PDF files with PHP and FPDF
  6. Perl Server Side CGI Scripting
  7. Sockets and TCP/IP Networking using PERL
  8. Assigning lists and arrays in PERL
  9. Send sms using perl
  10. Quick tutorial for handling exceptions in python
Categories: Perl

Leave a Reply