Skip to content

Instantly share code, notes, and snippets.

@wozniakjan
Last active March 30, 2016 00:46
Show Gist options
  • Save wozniakjan/4ddf553490d5628b6218 to your computer and use it in GitHub Desktop.
Save wozniakjan/4ddf553490d5628b6218 to your computer and use it in GitHub Desktop.
tiny script for refactoring
#!/usr/local/bin/bash
#or this !/bin/bash
trap 'echo "" ; exit 1' SIGINT
shopt -s globstar
usage() {
echo "Usage: [-i|--include=<.*>] [-d|--dir=<.*>] [-s|--semiauto] REGEXP_FROM STRING_TO"
}
TEMP=`getopt -o i:d:s --long include:,dir:,semiauto -n 'virefac' -- "$@"`
eval set -- "$TEMP"
REGEXP_FROM="${@: -2:1}"
STRING_TO="${@: -1:1}"
INCLUDE="*"
DIR="."
SEMIAUTO=false
while true ; do
case "$1" in
-i|--include) INCLUDE="$2" ; shift 2 ;;
-d|--dir) DIR="$2" ; shift 2 ;;
-s|--semiauto) SEMIAUTO=true ; shift 1 ;;
--) shift ; break ;;
*) usage ; exit 1 ;;
esac
done
for f in $DIR/**/$INCLUDE; do
str=`grep "$f" -e "$REGEXP_FROM"`
if [ ! -z "$str" ]; then
if [ "$SEMIAUTO" == true ]; then
sed -i "s/$REGEXP_FROM/$STRING_TO/g" "$f"
echo "Changed $f"
else
printf "%s" "Open $f? [y/n] "
read -n 1 INPUT
echo ""
if [[ "$INPUT" == "y" ]]; then
vim -c 'set ls=2' -c "%s/$REGEXP_FROM/$STRING_TO/cg" "$f"
fi
fi
fi
fn=`basename "$f" | grep "$REGEXP_FROM"`
if [ ! -z "$fn" ]; then
dst_name=`echo "$fn" | sed "s/$REGEXP_FROM/$STRING_TO/"`
dst=`dirname "$f"`"/$dst_name"
printf "%s\n $s" "Rename \"$f\" to" "\"$dst\"? [y/n] "
read -n 1 INPUT
echo ""
if [[ "$INPUT" == "y" ]]; then
mv "$f" "$dst"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment