Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- find $1 -type f -exec perl -e 's/'$2'/'$3'/g' -p -i {} ;
- # highlight the spots that will be modified (not specifying the file)
- find $1 -type f -exec grep -E "$2" --color {} ;
- # get confirmation
- read -p "Are you sure? " -n 1 -r
- if [[ $REPLY =~ ^[Yy]$ ]]
- then
- # make changes, and highlight the spots that were changed
- find $1 -type f -exec perl -e "s/$2/$3/g" -p -i {} ;
- echo ""
- find $1 -type f -exec grep -E "$3" --color {} ;
- else
- echo ""
- echo "Aborted!!"
- fi
- perl -e "s/$2/$3/g"
- use strict;
- use warnings;
- use autodie;
- use File::Find;
- use File::Temp;
- my($Search, $Replace, $Dir) = @ARGV;
- # Useful for testing
- run($Dir);
- sub run {
- my $dir = shift;
- find &replace_with_verify, $dir;
- }
- sub replace_with_verify {
- my $file = $_;
- return unless -f $file;
- print "File: $filen";
- if( verify($file, $Search) ) {
- replace($file, $Search, $Replace);
- print "nReplaced: $filen";
- highlight($file, $Replace);
- }
- else {
- print "Ignoring $filen";
- }
- print "n";
- }
- sub verify {
- my($file, $search) = @_;
- highlight($file, $search);
- print "Are you sure? [Yn] ";
- my $answer = <STDIN>;
- # default to yes
- return 0 if $answer =~ /^n/i;
- return 1;
- }
- sub replace {
- my($file, $search, $replace) = @_;
- open my $in, "<", $file;
- my $out = File::Temp->new;
- while(my $line = <$in>) {
- $line =~ s{$search}{$replace}g;
- print $out $line;
- }
- close $in;
- close $out;
- return rename $out->filename, $file;
- }
- sub highlight {
- my($file, $pattern) = @_;
- # Use PCRE grep. Should probably just do it in Perl to ensure accuracy.
- system "grep", "-P", "--color", $pattern, $file; # Should probably use a pager
- }
Add Comment
Please, Sign In to add comment