Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Shell Script for grep-based search and replace recursively in files
#!/bin/sh
SEARCH=$1
REPLACE=$2
function ConfirmOrExit() {
echo -n "Continue? (y / n) :"
read CONFIRM
if [ $CONFIRM != 'y' ]
then
exit
fi
}
if [ -z "$SEARCH" -o -z "$REPLACE" ]; then
echo "Searches for a specified string in the current directory and replaces all occurrences with the given replacement"
echo "Examples:"
echo " grepReplace great greater"
echo " grepReplace \"the best\" \"the worst\""
echo
echo "Note: both arguments are required to be non-empty"
exit
fi
GREP_EXCLUDE="grep -vE \.svn|\.git"
echo "Show potential results of searching for \"$SEARCH\" and replacing with \"$REPLACE\" in the current directory.";
ConfirmOrExit
echo
echo 'Before Replacement ############################################'
echo
grep --color -sF "$SEARCH" -r . | $GREP_EXCLUDE | grep --color -F "$SEARCH"
echo
echo 'After Replacement #############################################'
echo
grep -sF $GREP_OPT "$SEARCH" -r . | $GREP_EXCLUDE | sed "s/$SEARCH/$REPLACE/" | grep --color -F "$REPLACE"
echo
echo 'Perform the search and replace?'
ConfirmOrExit
grep -shlF "$SEARCH" -r . | $GREP_EXCLUDE | xargs sed "s/$SEARCH/$REPLACE/" -i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment