How to use sed to substitute strings which has "\" in it?

Abraham Jaison

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..

rudimeier

Stupid workaround, escape all the backslashes:

oldpassword="$(printf "$oldpassword" | sed 's/\\/\\\\/g')"
sed -i "s/$oldpassword/$newpassword/g" MyFile.txt

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

sed how to substitute when string has "http://" in it?

How to use sed to substitute LF with space, but not CRLF?

How to use substitute command in unix(vi or sed) to achieve the following results

How to use sed's substitute with a regex pattern as variable?

How to use variable character strings with 'substitute' function in R

Substitute values between 2 strings using sed

sed: regular expression,how to substitute?

How can I use SUBSTITUTE to substitute an apostrophe?

How to use sed to replace strings with categories?

how to substitute strings in a set of files with different strings?

How to substitute without creating intermediate file in sed?

How to substitute a character or expression for a newline using sed?

how to substitute slash in a file using sed

How to get sed to substitute for all but one character

How to use hasMany which has belongsTo in the child

How to use xpcall with a function which has parameters?

Substitute string in BASH with Sed (when it has special characters)

How to use for loops as a substitute for recursion?

how to use strings which annotation with @Value in order to join the other strings?

How to substitute runtime variables into strings in c?

How to substitute values in file between 2 strings

How to extract strings from a string which has bracket?

How to remove strings with word boundary which has special chars in java

How to get the Strings to show in message box which has for loop

How to style a charfield which has choices in it django or which widget to use?

How to use sed to find the strings between 2 patterns?

How to use sed to delete a line that has some determined fields?

Use sed command to wrap strings

How to use usecols elements which are regex rather than strings?