From c232c949320908be6bd6781b14e848ddfbc52ec8 Mon Sep 17 00:00:00 2001 From: Henrik Lissner Date: Thu, 4 Sep 2014 15:50:42 -0400 Subject: [PATCH] Add ag-replace script --- bin/ag-replace | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100755 bin/ag-replace diff --git a/bin/ag-replace b/bin/ag-replace new file mode 100755 index 00000000..77f27acb --- /dev/null +++ b/bin/ag-replace @@ -0,0 +1,51 @@ +#!/usr/bin/env bash + +# A simple script that uses ag 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") +GREEN=$(printf "\033[32m") +NC=$(printf "\033[0m") + +# Do a dry run for analysis +ag "$1" -s --nocolor --nogroup > /tmp/ag-repl +num=`cat /tmp/ag-repl | wc -l | sed -e "s/ //g"` +rm -rf /tmp/ag-repl +if [ "$num" -eq 0 ]; then + echo "No results were found!" + exit 1 +fi + +# Show the search/replace results +ag "$1" $3 -s --group --nocolor --nobreak \ + | perl -pe "s/(?<=.)$input/\033[4m$RED$replace$NC/g" \ + | perl -pe "s/^([^:]+)/$GREEN\$1$NC/g" + +# Ask for confirmation +echo +echo -n "Apply $num 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` + out=`echo "$files" | xargs perl -pi -e "s/$input/$replace/g"` + echo "$files" | sed -e "s/^/ ✓ /g" + + echo + echo "$num changes made!" +else + echo "Aborted!" + exit 2 +fi