diff --git a/bin/ag-replace b/bin/ag-replace deleted file mode 100755 index dbaa29e5..00000000 --- a/bin/ag-replace +++ /dev/null @@ -1,42 +0,0 @@ -#!/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") -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 diff --git a/bin/replace b/bin/replace new file mode 100755 index 00000000..bb085ff3 --- /dev/null +++ b/bin/replace @@ -0,0 +1,59 @@ +#!/usr/bin/env bash + +# A simple script that uses ag +# 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