2

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.

  • I assume that it did not work as desired. Please elaborate. What result do you expect? Which result do you get? – Yunnosch Feb 18 '20 at 15:37
  • What do you get for `echo $PASSWORD`? What do you get for `echo ${PASSWORD}`? – Yunnosch Feb 18 '20 at 15:38
  • If I echo it I get the correct value. When I run the sed I get no changes, even though when I check the file I get output. I have even gone as far as to.... `code` sed s/'"${PASSWORD)"'/Monday68\$/g" with no results – Andy Hollings Feb 18 '20 at 16:31
  • By both proposed ways? – Yunnosch Feb 18 '20 at 16:33
  • What happens if you do `PASSWORD='AsecretPassword\$'`? I.e. escape the dollar as you did in the code fragemtn in your comment. – Yunnosch Feb 18 '20 at 16:34
  • I am trying to search for the variable contents in a file and replace them, it works if the varable doe NOT contain a dollar sign. but does not match if it does – Andy Hollings Feb 18 '20 at 16:36
  • Yes I understood that. So what happens if you do as I proposed? – Yunnosch Feb 18 '20 at 16:36
  • I can't do that as the password is dynamic, I never know it so the sed command has to cope with special characters – Andy Hollings Feb 18 '20 at 16:38
  • Yes I understood that. The proposed experiment is for finding out the final solution. So what happens if you try? – Yunnosch Feb 18 '20 at 16:40
  • Yes that works, I expected it to be so, thanks for helping – Andy Hollings Feb 18 '20 at 16:45
  • So what you need to do is to use your variable in a way that the system does the correct escaping for you. Sadly, I am not so fluent and currently do not have an environment to try. – Yunnosch Feb 18 '20 at 16:48

1 Answers1

1

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.

brandizzi
  • 26,083
  • 8
  • 103
  • 158