helm/bin/ag-replace

43 lines
1 KiB
Plaintext
Raw Normal View History

2014-09-04 12:50:42 -07:00
#!/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
2014-09-05 11:26:55 -07:00
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
2014-09-04 12:50:42 -07:00
# Ask for confirmation
echo
2014-09-05 11:26:55 -07:00
echo -n "Apply changes? (y/n) "
2014-09-04 12:50:42 -07:00
read -n1 REPLY
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
2014-09-05 11:26:55 -07:00
# Now actually do the search replace! This is destructive. No, no
# backups are made. You better have read the earlier prompt!
2014-09-04 12:50:42 -07:00
files=`ag "$1" $3 -s --nogroup --nocolor --files-with-matches`
2014-09-05 11:26:55 -07:00
echo "$files" | xargs perl -pi -e "s/$input/$replace/g"
2014-09-04 12:50:42 -07:00
echo "$files" | sed -e "s/^/ ✓ /g"
echo
2014-09-05 11:26:55 -07:00
echo "Done!"
2014-09-04 12:50:42 -07:00
else
echo "Aborted!"
exit 2
fi