I have creatd a shell script which takes a string as input. If the string contains '$' or '&', then I need to raplace those characters with '\$' and '\&'. I could done that with sed command. After this I want to replace a word in a particular text file with that corresponding string.
Please see this section for more clarification.
This is my file.
test.txt
hello my root password is root.
Now, I want to change the word root with a string. The string can be anything which may include special characters like $ or &.
If I want to replace root with the string my&rootpa$$
, then it should looks like my\&rootpa\$\$
in text file.
This is my shell scipt
#!/bin/bash
dothis(){
rootpass=$(echo "$1" | sed -r 's/\$/\\$/g');
rootpass=$(echo "$rootpass" | sed -r 's/\&/\\&/g');
echo $rootpass;
sed -i "s/root/$rootpass/g" test.txt
}
dothis "my&rootpa$$";
This script works properly upto echo $rootpass
, which means when I echo the string it will display my\&rootpa\$\$.
But in the file it looks my&rootpa$$ instead of my\&rootpa\$\$. Whats wrong with the script.
Please advice.