0

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.

1 Answer 1

1

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\$\$.
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .