Created
June 2, 2014 16:12
Revisions
-
michaelpeternell created this gist
Jun 2, 2014 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,66 @@ #!/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($_); }