43 lines
1 KiB
Bash
Executable file
43 lines
1 KiB
Bash
Executable file
#!/usr/bin/env bash
|
|
|
|
# A simple script that uses ag <https://github.com/ggreer/the_silver_searcher> and perl
|
|
# to do a project-wide search/replace.
|
|
#
|
|
# Usage: ag-replace [pattern] [replace]
|
|
|
|
sanitize() {
|
|
echo "$1" | sed -e "s_/_\\\/_g"
|
|
}
|
|
|
|
input=$(sanitize "$1")
|
|
replace=$(sanitize "$2")
|
|
|
|
RED=$(printf "\033[31m")
|
|
NC=$(printf "\033[0m")
|
|
|
|
# Show the search/replace results
|
|
ag "$1" $3 -s --group --color --break --stats \
|
|
| perl -pe "s/(?<=.)$input/\033[4m$NC$RED$replace$NC/g" \
|
|
| perl -pe "s/^([0-9]+ matches$)/\n\$1/g" \
|
|
| less -XF
|
|
|
|
# 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!
|
|
files=`ag "$1" $3 -s --nogroup --nocolor --files-with-matches`
|
|
echo "$files" | xargs perl -pi -e "s/$input/$replace/g"
|
|
echo "$files" | sed -e "s/^/ ✓ /g"
|
|
|
|
echo
|
|
echo "Done!"
|
|
else
|
|
echo "Aborted!"
|
|
exit 2
|
|
fi
|