From 654fe60e3bd2b62e6d71f1f57a949543d77938a2 Mon Sep 17 00:00:00 2001 From: Henrik Lissner Date: Fri, 5 Sep 2014 14:26:55 -0400 Subject: [PATCH] refactor ag-replace --- bin/ag-replace | 27 +++++++++------------------ 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/bin/ag-replace b/bin/ag-replace index 77f27acb..dbaa29e5 100755 --- a/bin/ag-replace +++ b/bin/ag-replace @@ -13,38 +13,29 @@ 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" +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 $num changes? (y/n) " +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! + # 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" | xargs perl -pi -e "s/$input/$replace/g" echo "$files" | sed -e "s/^/ ✓ /g" echo - echo "$num changes made!" + echo "Done!" else echo "Aborted!" exit 2