Posted By

noah on 09/15/09


Tagged

regex search regexp example batch perl FileSystem maintenance regexen


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

icecreamboyy


Search and Replace Across Multiple Files with Perl


 / Published in: Perl
 

URL: http://gist.github.com/177086

This brief script replaces the batch search-and-replace tool in your commercial text editor. If batch file search and replacement is the only reason you need an IDE, you can adopt this script and go back to using Notepad (or better yet vi).

Thanks to JPinyan, who taught me the pattern shown below, back in 2001 on beginners.perl.org

The regular expression flags used here are explained in excellent detail in the best practices for regular expressions chapter of Perl Best Practices by Damian Conway.

  1. #!/usr/bin/perl -w
  2. use strict;
  3.  
  4. =head1 NAME
  5.  
  6. Search and Replace
  7.  
  8. =head1 SYNOPSIS
  9.  
  10.   perl search-replace.pl <files>
  11.  
  12. =head1 DESCRIPTION
  13.  
  14. Search and replace against a hard-coded regex. We'll use this script
  15. to replace JavaScript image paths. Maybe later it can
  16. be adapted into something more flexible.
  17.  
  18. =head2 Caveats
  19.  
  20. Silent in-place replacement without backup. Back up your assets (in
  21. source control) before testing this script.
  22.  
  23. =head2 The original one-liner
  24.  
  25.   perl -pi.bak -e 's/("http:\/\/images.example.com)([^:?<>]+\.(gif|jp(e)?g|png))/"\047 + \$.example.foo + "$2" + \047/g' global.js
  26.  
  27. =cut
  28.  
  29. $^I=".bak"; # change the files themselves instead of writing to STDOUT
  30. # use 'bak' as the extension for backup files
  31.  
  32. while (<>)
  33. {
  34. s{
  35. "http://images.example.com # match a double quote, followed by
  36. # the hard-coded URL we want to replace
  37.  
  38. ( # now start capturing to the $1 backreference variable
  39.  
  40. [^:?<>]+ # match any character except those not legal in file paths
  41.  
  42. \. # followed by a literal dot, followed by
  43.  
  44. (gif|jp(e)?g|png) # any of the usual image file extensions
  45.  
  46. ) # stop capturing
  47.  
  48. }{"' + \$.example.foo + '$1}xg; # print back a properly quoted JavaScript string of the form:
  49. # ' + $.example.foo + "<pathname>" + '
  50.  
  51. print $_;
  52. }

Report this snippet  

You need to login to post a comment.