Last active
December 21, 2021 19:41
-
-
Save zhangt58/3b7e73346d71ee0982caa5e54714f41d to your computer and use it in GitHub Desktop.
Code refactoring toolkit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
replace.shcan apply string substitutions on all the target files under defined path.Show usage message
Examples
replace.sh BitmapFromImage Bitmap.cppfiles larger than 1k, under directory/tmp/project:replace.sh int long -p '/tmp/peoject' -r "-name '*.cpp' -a -size '+1k'"