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.
Expand |
Embed | Plain Text
#!/usr/bin/perl -w use strict; =head1 NAME Search and Replace =head1 SYNOPSIS perl search-replace.pl <files> =head1 DESCRIPTION Search and replace against a hard-coded regex. We'll use this script to replace JavaScript image paths. Maybe later it can be adapted into something more flexible. =head2 Caveats Silent in-place replacement without backup. Back up your assets (in source control) before testing this script. =head2 The original one-liner perl -pi.bak -e 's/("http:\/\/images.example.com)([^:?<>]+\.(gif|jp(e)?g|png))/"\047 + \$.example.foo + "$2" + \047/g' global.js =cut $^I=".bak"; # change the files themselves instead of writing to STDOUT # use 'bak' as the extension for backup files while (<>) { s{ "http://images.example.com # match a double quote, followed by # the hard-coded URL we want to replace ( # now start capturing to the $1 backreference variable [^:?<>]+ # match any character except those not legal in file paths \. # followed by a literal dot, followed by (gif|jp(e)?g|png) # any of the usual image file extensions ) # stop capturing }{"' + \$.example.foo + '$1}xg; # print back a properly quoted JavaScript string of the form: # ' + $.example.foo + "<pathname>" + ' print $_; }
You need to login to post a comment.

