Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Recursively replacing a string in all files in a directory.
#!/bin/bash
#Define styls
RESET_STYLE=$(tput sgr0)
RED_COLOR=$(tput setaf 1)
GREEN_COLOR=$(tput setaf 2)
YELLO_COLOR=$(tput setaf 3)
BOLD=$(tput bold)
#Get the current OS name
PLATFORM=$(uname -s)
#User Inputs
read -p 'Please enter the search directory absolute Path</var/www/>: ' SEARCH_DIR
read -p 'Please enter the search word: ' SEARCH_WORD
read -p 'Please enter the replace word: ' REPLACE_WORD
#Iterate the files using the SEARCH_WORD
for f in `grep -lr "$SEARCH_WORD" $SEARCH_DIR`
do
echo "${GREEN_COLOR} '$SEARCH_WORD' find in ${RESET_STYLE} ${YELLO_COLOR} $f ${RESET_STYLE}"
done
#Count the total number of files
COUNT_FILES=`grep -lr "$SEARCH_WORD" $SEARCH_DIR | wc -l`
#Set Nouns
FILE_NOUNS=`[[ $COUNT_FILES -gt 1 ]] && echo 'files' || echo 'file'`
echo "********************************************"
echo "${GREEN_COLOR} The '$SEARCH_WORD' word find in ${BOLD} $COUNT_FILES $FILE_NOUNS ${RESET_STYLE}"
echo "********************************************"
#Check users input and replace the word
echo "${GREEN_COLOR}Do you want to replace $SEARCH_WORD to $REPLACE_WORD? [Y,n]${RESET_STYLE}"
read input
if [[ $input == "Y" || $input == "y" ]]; then
for f in `grep -lr "$SEARCH_WORD" $SEARCH_DIR`
do
#Check the OS
if [[ $PLATFORM == "Darwin" ]]; then
sed -i '' "s/${SEARCH_WORD}/${REPLACE_WORD}/g" $f;
else
sed -i "s/${SEARCH_WORD}/${REPLACE_WORD}/g" $f;
fi
echo "${GREEN_COLOR} '$SEARCH_WORD' replacing to '$REPLACE_WORD' in $f file. ${RESET_STYLE}"
done
else
echo "${RED_COLOR}${BOLD}EXIT!!!${RESET_STYLE}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.