Skip to content

Instantly share code, notes, and snippets.

@zhangt58
Last active December 21, 2021 19:41
Show Gist options
  • Select an option

  • Save zhangt58/3b7e73346d71ee0982caa5e54714f41d to your computer and use it in GitHub Desktop.

Select an option

Save zhangt58/3b7e73346d71ee0982caa5e54714f41d to your computer and use it in GitHub Desktop.
Code refactoring toolkit
#!/bin/bash
# Code refactoring tool:
#
# Replace $OLD with $NEW for files
#
# Tong Zhang <zhangt@frib.msu.edu>
# 2017-07-21 10:52:37 AM EDT
#
if [[ $# -lt 2 ]]; then
echo "Usage: `basename $0` old_string new_string [options]"
echo
echo "Escape special char with \\."
echo
echo "Options:"
echo " -p, --path path for recursively file searching"
echo " -r, --rule search rules, see find(1)"
echo
echo "Default settings for path is current working directory,"
echo "rule is find all Python source files with ext of '.py' or '.PY'."
echo
echo "Examples:"
echo
echo "Replace image to Image for all .cpp files under /tmp/project1 directory"
echo "$ `basename $0` image Image -p '/tmp/project1' -r \"-name '*.cpp'\" "
echo
echo "Replace \"xyz\" to \"abc\" for all .c files under /tmp/project1 directory"
echo "$ `basename $0` \\\\\\\"xyz\\\\\\\" \\\\\\\"abc\\\\\\\" -p '/tmp/project1' -r \"-name '*.c'\" "
exit 1
fi
FIND=`which find`
GREP=`which grep`
SED=`which sed`
OLD=$1
NEW=$2
while [[ $# -gt 2 ]]
do
k="$3"
case $k in
-p|--path)
path="$4"
shift
;;
-r|--rule)
rule="$4"
shift
;;
esac
shift
done
path=${path:-.}
rule=${rule:-"-iname '*.py'"}
files=$(eval "${FIND} ${path} ${rule} -exec ${GREP} -H "$OLD" {} \;" \
| awk -F':' '{print $1}' \
| uniq | tr '\n' ' ')
for f in $files
do
echo "Replacing "$OLD" to $NEW for $f ..."
${SED} -i "s/$OLD/$NEW/g" $f
done
@zhangt58
Copy link
Author

replace.sh can apply string substitutions on all the target files under defined path.

Show usage message

$ replace.sh
Usage: replace.sh old_string new_string [options]

Options:
 -p, --path    path for recursively file searching
 -r, --rule    search rules, see find(1)

Default settings for path is current working directory,
rule is find all Python source files with ext of '.py' or '.PY'.

Examples

  1. Replace "BitmapFromImage" with "Bitmap" in current working directory for all Python source files:
    replace.sh BitmapFromImage Bitmap
  2. Replace "int" to "long" for all .cpp files larger than 1k, under directory /tmp/project:
    replace.sh int long -p '/tmp/peoject' -r "-name '*.cpp' -a -size '+1k'"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment