Guest User

Untitled

a guest
Jan 19th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. find $1 -type f -exec perl -e 's/'$2'/'$3'/g' -p -i {} ;
  2.  
  3. # highlight the spots that will be modified (not specifying the file)
  4. find $1 -type f -exec grep -E "$2" --color {} ;
  5. # get confirmation
  6. read -p "Are you sure? " -n 1 -r
  7. if [[ $REPLY =~ ^[Yy]$ ]]
  8. then
  9. # make changes, and highlight the spots that were changed
  10. find $1 -type f -exec perl -e "s/$2/$3/g" -p -i {} ;
  11. echo ""
  12. find $1 -type f -exec grep -E "$3" --color {} ;
  13. else
  14. echo ""
  15. echo "Aborted!!"
  16. fi
  17.  
  18. perl -e "s/$2/$3/g"
  19.  
  20. use strict;
  21. use warnings;
  22.  
  23. use autodie;
  24. use File::Find;
  25. use File::Temp;
  26.  
  27. my($Search, $Replace, $Dir) = @ARGV;
  28.  
  29. # Useful for testing
  30. run($Dir);
  31.  
  32. sub run {
  33. my $dir = shift;
  34. find &replace_with_verify, $dir;
  35. }
  36.  
  37. sub replace_with_verify {
  38. my $file = $_;
  39. return unless -f $file;
  40.  
  41. print "File: $filen";
  42.  
  43. if( verify($file, $Search) ) {
  44. replace($file, $Search, $Replace);
  45. print "nReplaced: $filen";
  46. highlight($file, $Replace);
  47. }
  48. else {
  49. print "Ignoring $filen";
  50. }
  51.  
  52. print "n";
  53. }
  54.  
  55. sub verify {
  56. my($file, $search) = @_;
  57.  
  58. highlight($file, $search);
  59.  
  60. print "Are you sure? [Yn] ";
  61. my $answer = <STDIN>;
  62.  
  63. # default to yes
  64. return 0 if $answer =~ /^n/i;
  65. return 1;
  66. }
  67.  
  68. sub replace {
  69. my($file, $search, $replace) = @_;
  70.  
  71. open my $in, "<", $file;
  72. my $out = File::Temp->new;
  73.  
  74. while(my $line = <$in>) {
  75. $line =~ s{$search}{$replace}g;
  76. print $out $line;
  77. }
  78.  
  79. close $in;
  80. close $out;
  81.  
  82. return rename $out->filename, $file;
  83. }
  84.  
  85. sub highlight {
  86. my($file, $pattern) = @_;
  87.  
  88. # Use PCRE grep. Should probably just do it in Perl to ensure accuracy.
  89. system "grep", "-P", "--color", $pattern, $file; # Should probably use a pager
  90. }
Add Comment
Please, Sign In to add comment