replace.sh

Friday, May 13th, 2005 - Español English

Poor man’s replace in files. Get it. Or see it…

  1. #!/bin/bash
  2. #
  3. # Thu May 12 12:02:01 CEST 2005 * Miguel de Benito <nonick AT 8027 DOT org>
  4. #
  5. # Poor man's "replace in files"...
  6. #
  7.  
  8. ##################
  9. # Load lib
  10. #
  11. if [ ! -f ~/bin/messages.sh ]; then
  12. echo "~/bin/messages.sh is required but not found. Bye..."
  13. exit 1
  14. fi
  15. . ~/bin/messages.sh
  16.  
  17. TMPPATH="/tmp/replace"
  18.  
  19. ##################
  20. # Check params
  21. #
  22. if (( ${#@} < 3 ))
  23. then
  24. echo
  25. echo "Usage: $0 <directory> <string> <replacement> <extension>"
  26. echo
  27. echo " <string> is taken as a Perl regex"
  28. echo " <replacement> must have any $ escaped"
  29. echo " <extension> is optional"
  30. exit 1
  31. fi
  32.  
  33. DIR=$1
  34. STR=$2
  35. REP=$3
  36. EXT=$4
  37.  
  38. if [ ! -d "$DIR" ]
  39. then
  40. error_msg "Either '$DIR' is not a directory or it is not readable."
  41. exit 2
  42. fi
  43.  
  44. # Replace . with working directory
  45. [ "$DIR" == "." ] && DIR=$(pwd)
  46.  
  47. if [ -z "$EXT" ]
  48. then
  49. EXT='*'
  50. extmsg="every file"
  51. else
  52. extmsg="'$EXT' files"
  53. fi
  54.  
  55.  
  56. ##################
  57. # Go
  58. #
  59. echo
  60. echo "Replacing '$STR' with '$REP' in $extmsg of directory '$DIR':"
  61. echo
  62.  
  63.  
  64. run_cmd "Creating temporary directory... " "/bin/mkdir -p $TMPPATH/$DIR"
  65.  
  66. files=$(find $1 -maxdepth 1 -name "*$EXT")
  67. [ -z "$files" ] && info_msg "No files match the extension pattern" && exit 0;
  68.  
  69. for file in $files
  70. do
  71. lines=$(grep -clP "$STR" $file)
  72. if [ ! -z "$lines" ]
  73. then
  74. echo " $file"
  75. name=$(basename $file)
  76. tmp=$TMPPATH/$name~~
  77. cat $file | perl -ne "s/$STR/$REP/; print $_;" > $tmp
  78. cp $tmp $DIR/$name
  79. fi
  80. done
  81.  
  82. # TODO: check return codes and ask if we should revert changes
  83.  

One Response to “ replace.sh ”

  1. Programming Tutorials Says:

    Programming Tutorials

    I couldn’t understand some parts of this article, but it sounds interesting

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>