Created
June 2, 2014 16:12
-
-
Save michaelpeternell/2a95b6445b4e9ad9b115 to your computer and use it in GitHub Desktop.
Search and replace on a whole directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
# by Michael Peternell | |
# Created: 2013 | |
# Last modified: 2013 | |
# Search and replace on a whole directory. | |
# filenames are also searched and replaced. | |
# recursive. | |
# (Git files are excluded from the search. (when filename contains ".git")) | |
use strict; | |
my $search = $ARGV[0]; | |
my $replace = $ARGV[1]; | |
sub refactor | |
{ | |
my $fn = shift; | |
#rename file | |
$fn =~ m:^(.+)/([^/]+)$:; | |
my $dirname = $1; | |
my $basename = $2; | |
if($basename =~ m($search)) { | |
$basename =~ s/$search/$replace/g; | |
my $old_fn = $fn; | |
$fn = "$dirname/$basename"; | |
print "In $dirname: Renaming $old_fn to $fn\n"; | |
rename $old_fn, $fn; | |
} | |
#activate slurp mode | |
local $/ = undef; | |
#search | |
unless(open F, "<", $fn) { | |
warn("Cannot open $fn: $!"); | |
return; | |
} | |
my $contents = <F>; | |
close F; | |
#replace | |
if($contents =~ m/$search/) | |
{ | |
print "Substituting in $fn\n"; | |
$contents =~ s/$search/$replace/g; | |
unless(open F, ">", $fn) { | |
warn("Cannot open for writing $fn: $!"); | |
return; | |
} | |
print F $contents; | |
close F; | |
} | |
} | |
if(!$search || !$replace) { | |
die("Usage: $0 'search-string' 'replace-string'\n"); | |
} | |
open FILES, q(find . -type f | grep -v '/\\.git/' |) or die "Error in find: $!"; | |
while(<FILES>) { | |
chomp; | |
refactor($_); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment