Skip to content

Instantly share code, notes, and snippets.

@markusfisch
Last active January 15, 2016 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markusfisch/894450 to your computer and use it in GitHub Desktop.
Save markusfisch/894450 to your computer and use it in GitHub Desktop.
bash script to exchange a literal in files and file names (can be used to completely rename a Xcode project or to refactor something throughout your whole project, use with caution!)
#!/usr/bin/env bash
# Refactor file and directory names as well as words in files
#
# @param 1 - case-sensitive pattern to replace
# @param 2 - replacement string
# @param 3 - working directory (optional)
refactor()
{
local PATTERN=$1
local REPLACEMENT=$2
local DIR=${3:-.}
(( $# < 2 )) && {
echo "usage: ${0##*/} PATTERN REPLACEMENT [DIR]"
return 1
}
# rename directories before files
local TYPE REFACTORED
for TYPE in d f
do
find "$DIR" -type "$TYPE" -name "*$PATTERN*" | while read -r
do
REFACTORED=${REPLY//$PATTERN/$REPLACEMENT}
echo "renaming $REPLY to $REFACTORED"
mv "$REPLY" "$REFACTORED"
done
done
local TMP=".tmp-${0##*/}-$$"
grep -rl "$PATTERN" "$DIR"/* | while read -r
do
echo "replacing pattern in $REPLY"
sed -e "s/$PATTERN/$REPLACEMENT/g" < "$REPLY" > "$TMP" &&
cat "$TMP" > "$REPLY"
rm -f "$TMP"
done
}
if [ "${BASH_SOURCE[0]}" == "$0" ]
then
refactor "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment