ag-replace -> replace

This commit is contained in:
Henrik Lissner 2014-09-06 12:09:53 -04:00
parent 9f1e1646df
commit 4dbf8e592c
2 changed files with 59 additions and 42 deletions

View file

@ -1,42 +0,0 @@
#!/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

59
bin/replace Executable file
View file

@ -0,0 +1,59 @@
#!/usr/bin/env bash
# A simple script that uses ag
# <https://github.com/ggreer/the_silver_searcher> 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