60 lines
1.4 KiB
Plaintext
60 lines
1.4 KiB
Plaintext
|
#!/usr/bin/env bash
|
||
|
|
||
|
# A simple script that uses ag
|
||
|
# <https://github.com/ggreer/the_silver_searcher> and perl to perform
|
||
|
# a project-wide search and replace; it shows you the results and asks
|
||
|
# for confirmation before committing the changes.
|
||
|
#
|
||
|
# Usage: replace [pattern] [replace] [options for ag]
|
||
|
|
||
|
TMP_FILE="/tmp/ag-repl"
|
||
|
RED=`printf "\033[31m"`
|
||
|
NC=`printf "\033[0m"`
|
||
|
|
||
|
sanitize() {
|
||
|
# For text that we interpolate into perl search/replace regex
|
||
|
echo "$1" | sed -e "s_/_\\\/_g"
|
||
|
}
|
||
|
|
||
|
# Begin
|
||
|
input=$1
|
||
|
search=`sanitize "$1"`
|
||
|
replace=`sanitize "$2"`
|
||
|
|
||
|
shift
|
||
|
shift
|
||
|
|
||
|
# Show the search/replace results
|
||
|
if ag $input $* -s --group --color --break --stats \
|
||
|
| perl -p -e "s/(?<=.)$search/$NC$RED$replace$NC/g" \
|
||
|
| perl -p -e "s/^([0-9]+ matches$)/\n\$1/g" \
|
||
|
> "$TMP_FILE"; then
|
||
|
|
||
|
# Show the results
|
||
|
less -XF "$TMP_FILE"
|
||
|
|
||
|
# Calculate if there were results
|
||
|
lines=`wc -l $TMP_FILE | awk '{print $1}'`
|
||
|
rm -rf "$TMP_FILE"
|
||
|
[ "$lines" -lt 6 ] && exit 2
|
||
|
|
||
|
# Ask for confirmation
|
||
|
echo
|
||
|
echo -n "Apply changes? (y/n) "
|
||
|
read -n1 REPLY
|
||
|
echo
|
||
|
|
||
|
if [[ $REPLY =~ ^[Yy]$ ]]; then
|
||
|
# Now actually do the search replace! This is destructive. No, no
|
||
|
# backups are made. You better have read the earlier prompt!
|
||
|
ag -l $input $* | xargs perl -pi -e "s/$search/$replace/g"
|
||
|
echo "Done!"
|
||
|
exit
|
||
|
else
|
||
|
echo $RED"Aborted!"$NC
|
||
|
exit 3
|
||
|
fi
|
||
|
fi
|
||
|
|
||
|
exit 1
|