Search code examples
stringshellescapingksh

Trying to replace a value with a string containing backslash \ in a file


I could really use your help here.

What I want to do :
I have an encrypted password I want to write in a property file. Let's say I have this password stored in $password and I want to write it as value to a key named "passKey" in my.varfile file.

Here's the command I used so far to do so :
sed -i "s|passKey=[^ ]*|passKey=$password|" /path/to/my.varfile

Problem :
It worked just fine until I got an encrypted password containing a backslash \
=> what happens with it is that sed interprets the backslash as an escape character, thus messing with the password.

For instance, when I have a pass like : 205RjIiajQ\=\=
It gets written in my file as : 205RjIiajQ==

I tried many things, like replacing \ with a \\ in my password to actually escape the backslash, without success.

Any ideas on how to do this ?
I'm also open to suggestions such as trying to do it with anything else than sed.

(Note that - unfortunately :p - I'm using ksh here, not bash)

Thanks
T.


Solution

  • One idea would be to use pattern substitution (see section 4.5.4) to add an escape character (\) to each occurrence of \ in $password.

    Let's say we have the following password:

    $ password='205R\\\jIiajQ\\=\='
    

    OP's current sed solution (and incorrect result):

    $ sed "s|passKey=[^ ]*|passKey=${password}|" file
    passKey=205R\jIiajQ\==
    

    Let's use parameter substitution to replace each \ with \\:

    $ password="${password//\\/\\\\}"       # we have to escape each `\` to keep it from being treated as an escape character
    $ echo "${password}"
    205R\\\\\\jIiajQ\\\\=\\=
    

    OP's sed solution with this new $password (and correct result):

    $ sed "s|passKey=[^ ]*|passKey=${password}|" file
    passKey=205R\\\jIiajQ\\=\=
    

    Here's a ksh93 fiddle

    NOTES:

    • once OP verifies this solution works the -i option can be added back into the sed command as needed
    • if there's a need to maintain the original $password value, a new variable can be used to hold the 'escaped' string (eg, newpwd="${password//\\/\\\\}" ; sed "s|....|passkey=${newpwd}|" file)