I m having difficulty with sed, a variable contains Dollar Sign like this…
JavaScript
x
PASSWORD='AsecretPassword$'
I am trying to ‘cleanse’ and outputfile of a password with.
JavaScript
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:
JavaScript
$ cat outputfile
commonpassword
AsecretPassword$
abc123
If you had control over the value of the pattern, you could just escape the dollar sign:
JavaScript
$ sed 's,AsecretPassword$,ChangeMe,g' outputfile
commonpassword
ChangeMe
abc123
Alas, we don’t have, but we can use sed to escape the variable value:
JavaScript
$ echo $PASSWORD | sed -e 's/$/\$/g'
AsecretPassword$
Fortunately, we can get the output of one command as part of another by using command substitution:
JavaScript
$ 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!
JavaScript
$ 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.