Created
August 23, 2019 13:07
-
-
Save pitabas106/9da5c862528194b6970ea3c4e9d19426 to your computer and use it in GitHub Desktop.
Recursively replacing a string in all files in a directory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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