Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.


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

    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.

share|improve this question
up vote 1 down vote accepted

You have to escape $ and & multiple times, because when using the sed -i command they need to be escaped as well. If not escaped multiple times they will be interpreted as single & and $ signs.

    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 worked for me. The output is:


And test looks like this after execution:

user@host:~# cat test.txt
hello my my\&rootpa\$\$ password is my\&rootpa\$\$.
share|improve this answer
This worked perfect. Thanks chaos. – Uvais Ibrahim Jan 22 '14 at 8:47

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.