I have this bash script that is basically a search/replace in a text file.
I am running into issues when a user sends in a string that has special characters (quotes, spaces, =s, etc). So I think that I want to put a \ in front of each special character. Can I do it in one command or does each character needs its own command?
Or I am going about this in the wrong way?
Heres the code.
Code:
#!/bin/bash
echo "Hello!"
echo "Enter a string to be replaced:"
read old
echo "Enter a string that will replace the above string:"
read new
echo "Enter the name of a file where you want this to take place:"
read filename
#Checks to see if the file exists in the current directory
if [ -e $filename ]
then
#saves a backup of the original file
oldfile=$filename"_old_"`date '+%m%d%Y'`
cat $filename > $oldfile
#makes sure the quotes are read in correctly
old=${old//"\""/"\\\""}
new=${new//"\""/"\\\""}
#performs the replacement
sed -i 's/'$old'/'$new'/g' $filename
echo "Success! Your file has been updated"
else
echo "The filename that you typed in does not exist."
fi