1

I have a file named MyFile.txt with the following contents:

Username=myusername
EncryptedPassword=9k3S+sS3g\=\=

Each time I need to change the username and password I run a shell script. In the shell script I store the save username and password to two variables namely:

oldusername="myusername"
oldpassword="9k3S+sS3g\=\="

newusername="mynewusername"

newpassword="U8djlk+h\=="

sed -i "s/$oldusername/$newusername/g" MyFile.txt

sed -i "s/$oldpassword/$newpassword/g" MyFile.txt

The first sed works properly and replaces the username, however the second sed command doesn't work and the password is not changed in the file. I think it is because of the "\" character present in the variables.

Could someone help me out with this and let me know how to go about it?

Thanks..

3 Answers3

0

Stupid workaround, escape all the backslashes:

oldpassword="$(printf "$oldpassword" | sed 's/\\/\\\\/g')"
sed -i "s/$oldpassword/$newpassword/g" MyFile.txt
rudimeier
  • 10,315
0
$ cat MyFile.txt 
Username=myusername
EncryptedPassword=9k3S+sS3g\=\=
$ oldusername="myusername"
$ oldpassword="9k3S+sS3g\=\="
$ newusername="mynewusername"
$ newpassword="U8djlk+h\=="

$ perl -pe "s/\Q$oldusername/q($newusername)/e ; s/\Q$oldpassword/q($newpassword)/e" MyFile.txt
Username=mynewusername
EncryptedPassword=U8djlk+h\==

From perldoc for \Q and q()

Returns the value of EXPR with all the ASCII non-"word" characters backslashed. (That is, all ASCII characters not matching /[A-Za-z_0-9]/ will be preceded by a backslash in the returned string, regardless of any locale settings.) This is the internal function implementing the \Q escape in double-quoted strings

Once result is okay, use perl -i -pe for inplace editing, same as sed

Sundeep
  • 12,008
-1

Have you echo'd the contents of $oldpassword? The backslashes will be missing from $oldpassword,

$ oldpassword=9k3S+sS3g\=\=
$ echo $oldpassword
9k3S+sS3g==

As such the match will fail.

If you want the backslash characters in there, put single quotes around the value you assign to oldpassword to stop the shell from interpreting them as escape sequences, i.e., make the value a literal string,

$ oldpassword='9k3S+sS3g\=\=
ocurran
  • 204