Posted By

tedw on 08/27/13


Tagged

renamesearchreplacemovereferences


Versions (?)

RenameFileAndUpdateReferences.sh


 / Published in: Bash
 

This script will rename a file from the first parameter to the second parameter and do a sed replace of all references of the first parameter with the second parameter

For example: RenameFileAndUpdateReferences.sh filename-dc80c59.css filename.css

  1. #!/bin/sh
  2. # Make sure file is saved with Unix encoding (dos2unix)
  3. #
  4. # This script will rename a file from the first parameter to the second parameter
  5. # and do a sed replace of all references of the first parameter with the second parameter
  6. #
  7. # For example:
  8. # RenameFileAndUpdateReferences.sh filename-dc80c59.css filename.css
  9. if [ $# -lt 2 ] ; then
  10. echo
  11. echo Wrong number of parameters.
  12. echo Try again using the following format:
  13. echo RenameFileAndUpdateReferences.sh findstring replacestring
  14. echo
  15. echo example:
  16. echo "RenameFileAndUpdateReferences.sh \"filenameABC.ext\" \"filenameDEF.ext\""
  17. echo
  18. exit 1
  19. fi
  20.  
  21. IFS=$'\n'
  22.  
  23. if [[ "$3" == 'go' ]]; then
  24. TIMESTAMP=$(date +%s)
  25. BACKUP_EXT="rfaur_saved"
  26. BACKUP_SUFFIX=".$TIMESTAMP.$BACKUP_EXT"
  27. COUNTER=0
  28.  
  29. echo "Replacing files..."
  30. for FILENAME in $(find . -type f -exec grep -l "$1" {} \;); do
  31. if [[ "$FILENAME" != *.$BACKUP_EXT* ]]; then # don't text in backup files
  32. echo " working on file \"$FILENAME\""
  33. BACKUP_FILENAME="$FILENAME$BACKUP_SUFFIX"
  34. ###echo "$BACKUP_FILENAME"
  35. cp "$FILENAME" "$BACKUP_FILENAME"
  36. sed "s#$1#$2#g" "$BACKUP_FILENAME" > "$FILENAME"
  37. ### rm "$BACKUP_FILENAME" # uncomment this line to remove backup file
  38. COUNTER=$[$COUNTER +1]
  39. fi
  40. done
  41. echo "String replaced in $COUNTER file(s) (backup timestamp is $TIMESTAMP)"
  42.  
  43. COUNTER=0
  44. echo "Renaming files..."
  45. for FILENAME in $(find . -type f -name "$1"); do
  46. NEW_FILENAME="$(dirname ${FILENAME})/$2" # e.g. some/path/to/the/newfilename
  47. echo " renaming file \"$FILENAME\" to \"$NEW_FILENAME\""
  48. if [ -e $NEW_FILENAME ]; then
  49. BACKUP_FILENAME="$NEW_FILENAME$BACKUP_SUFFIX"
  50. echo " \"$NEW_FILENAME\" already exists, backing up to \"$BACKUP_FILENAME\""
  51. cp "$NEW_FILENAME" "$BACKUP_FILENAME"
  52. fi
  53. mv $FILENAME $NEW_FILENAME
  54. COUNTER=$[$COUNTER +1]
  55. done
  56. echo "$COUNTER file(s) renamed"
  57. echo "-- DONE --"
  58. else
  59. echo "All instances of \"$1\" will be changed to \"$2\" in the following files:"
  60. find . -type f -exec grep -n "$1" {} /dev/null \;
  61. echo
  62.  
  63. echo "The following files will be renamed:"
  64. find . -type f -name "$1"
  65. echo
  66.  
  67. echo "Preview done, add 'go' as the 3rd argument to execute changes"
  68. fi

Report this snippet  

You need to login to post a comment.