Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

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.

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

my\\\&rootpa\\\$\\\$

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 at 8:47

Your Answer

 
discard

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.