Replace string on a folder recursively via grep and sed
This is the script I created to replace a string on folders recursively
Many thanks to serverfault users and othe person that helped me create this script
#!/bin/bash
# user input
echo "Enter string to be replaced"
read OLDSTRING
echo "Enter string to be placed"
read NEWSTRING
echo "==================================="
echo "string to be replaced is $OLDSTRING"
echo "string to be placed is $NEWSTRING "
echo "==================================="
oldstr=$OLDSTRING #string to be replaced
newstr=$NEWSTRING #new string to be placed
echo "Enter folder path where we will find the string"
read FOLDERPATH
### grep oldstring and output it in grep_output.txt STEP1
grep -rl $oldstr $FOLDERPATH > grep_output.txt
### since there might be spaces or special characters on filenames, use sed to enclose them with quote and output in sed_output.txt STEP2
#for i in `cat grep_output.txt`
#do sed -e "s/'/'\\\\''/g;s/\(.*\)/'\1'/" grep_output.txt > sed_output.txt
#done
for i in `cat grep_output.txt`
do sed -i "s/$oldstr/$newstr/g" $i > sed_output_new_old_string.txt
done
## NOTE ##
# 2013 latest
## STEP 2 Seems not working just edit the grep_output and remove the spaces
# If this doesnt work, on the first time, do again then comment STEP 1 and STEP 2# Also try to remove the spaces on the grep_output
Many thanks to serverfault users and othe person that helped me create this script
#!/bin/bash
# user input
echo "Enter string to be replaced"
read OLDSTRING
echo "Enter string to be placed"
read NEWSTRING
echo "==================================="
echo "string to be replaced is $OLDSTRING"
echo "string to be placed is $NEWSTRING "
echo "==================================="
oldstr=$OLDSTRING #string to be replaced
newstr=$NEWSTRING #new string to be placed
echo "Enter folder path where we will find the string"
read FOLDERPATH
### grep oldstring and output it in grep_output.txt STEP1
grep -rl $oldstr $FOLDERPATH > grep_output.txt
### since there might be spaces or special characters on filenames, use sed to enclose them with quote and output in sed_output.txt STEP2
#for i in `cat grep_output.txt`
#do sed -e "s/'/'\\\\''/g;s/\(.*\)/'\1'/" grep_output.txt > sed_output.txt
#done
for i in `cat grep_output.txt`
do sed -i "s/$oldstr/$newstr/g" $i > sed_output_new_old_string.txt
done
## NOTE ##
# 2013 latest
## STEP 2 Seems not working just edit the grep_output and remove the spaces
# If this doesnt work, on the first time, do again then comment STEP 1 and STEP 2# Also try to remove the spaces on the grep_output
Comments