Skip to content
Advertisement

SED Variable contains Dollar Sign

I m having difficulty with sed, a variable contains Dollar Sign like this…

PASSWORD='AsecretPassword$'

I am trying to ‘cleanse’ and outputfile of a password with.

sed -i "s,$PASSWORD,ChangeMePassword,g" outputfile.json 

I have tried every version of quotes you can imagine. please help.

Advertisement

Answer

Well, let us suppose you have this file:

$ cat outputfile 
commonpassword
AsecretPassword$
abc123

If you had control over the value of the pattern, you could just escape the dollar sign:

$ sed 's,AsecretPassword$,ChangeMe,g' outputfile
commonpassword
ChangeMe
abc123

Alas, we don’t have, but we can use sed to escape the variable value:

 $ echo $PASSWORD | sed -e 's/$/\$/g'
 AsecretPassword$

Fortunately, we can get the output of one command as part of another by using command substitution:

$ echo "Command substitution: $(echo $PASSWORD | sed -e 's/$/\$/g') Cool, right?"
Command substitution: AsecretPassword$ Cool, right?

…so we just need to do it on our original command!

$ sed "s,$(echo $PASSWORD| sed -e 's/$/\&/g'),ChangeMe,g" outputfile
commonpassword
ChangeMe
abc123

In this case, we just escaped one special character. There are some more on sed, so this Q&A can be helpful in the general case.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement