Skip to content

Instantly share code, notes, and snippets.

@dsummersl
Forked from jcamenisch/.profile fragment
Created December 5, 2012 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsummersl/4216704 to your computer and use it in GitHub Desktop.
Save dsummersl/4216704 to your computer and use it in GitHub Desktop.
Lightning-fast project-wide find/replace with git grep and sed -- with confirm option.
gg_replace() {
if [[ "$#" == "0" ]]; then
echo 'Usage:'
echo ' gg_replace term replacement file_mask'
echo ' gg_replace [-c] term replacement file_mask'
echo
echo 'Options:'
echo ' -c == confirm. Allows you to interactively confirm each modification.'
echo
echo 'Example:'
echo ' gg_replace cappuchino cappuccino *.html'
echo
else
confirm=0
if [[ "$1" = "-c" ]]; then
confirm=1
shift
fi
find=$1; shift
replace=$1; shift
ORIG_GLOBIGNORE=$GLOBIGNORE
ORIG_IFS=$IFS
GLOBIGNORE=*.*
IFS=''
if [[ "$#" = "0" ]]; then
set -- ' ' $@
fi
while [[ "$#" -gt "0" ]]; do
for file in `git grep -l $find -- $1`; do
if [[ "$confirm" -eq "1" ]]; then
if [[ "$SHELL" == *zsh* ]]; then
echo -n "${file} | Replace? [y/n]"
read -q REPLY
else
read -p "${file} | Replace? [y/n] " -n 1 -r
fi
if [[ $REPLY =~ ^[Yy]$ ]]; then
sed -i '' -e "s/$find/$replace/g" $file
fi
else
echo "doNOTconfirm"
sed -i '' -e "s/$find/$replace/g" $file
fi
done
shift
done
GLOBIGNORE=$ORIG_GLOBIGNORE
IFS=$ORIG_IFS
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment