Galet
Galet

Reputation: 6279

Replace string with special characters value using sed in Ubuntu

Following is the xml file in which STORAGE_ACCOUNT_KEY should be replaced with EoKpaH0W/kqTv9awgIpQX5s+qQwGzXUSxMxhRjfSWG7SIUTWhut1OYQkNxhb3/9UKGf+g4tc3UaC0zKMTSrTNg==

   <property>
      <name>fs.azure.account.key.storageaccountname.blob.core.windows.net</name>
      <value>STORAGE_ACCOUNT_KEY</value>
   </property>

I have tried the following. But nothing helps me solve it.

  1. Using / after s and before g

sed -i "s/STORAGE_ACCOUNT_KEY/EoKpaH0W/kqTv9awgIpQX5s+qQwGzXUSxMxhRjfSWG7SIUTWhut1OYQkNxhb3/9UKGf+g4tc3UaC0zKMTSrTNg==/g" test.xml

Error:-

sed: -e expression #1, char 32: unknown option to `s'
  1. Using | after s and before g
sed -i "s|STORAGE_ACCOUNT_KEY/EoKpaH0W/kqTv9awgIpQX5s+qQwGzXUSxMxhRjfSWG7SIUTWhut1OYQkNxhb3/9UKGf+g4tc3UaC0zKMTSrTNg==|g" test.xml

Error:-

sed: -e expression #1, char 112: unterminated `s' command

Note:- $STORAGE_ACCOUNT_KEY is a dynamic variable as below

sed -i "s|STORAGE_ACCOUNT_KEY/$STORAGE_ACCOUNT_KEY|g"

Upvotes: 1

Views: 499

Answers (1)

oliv
oliv

Reputation: 13249

To replace XML, I would adivse to use an XML parser (for example xmllint) instead of sed.

That said, your sed expression is wrong.

sed s command uses 3 delimiters (any printable character you want), but these 3 must be the same and is defined by the one right after the s command.

s/foo/bar/g   # right
s|foo|bar|g   # right
s|foo/bar|g   # wrong

Since you replace a string with a base64 string, you should not use any of the base64 character, so don't use / as a sed delimiter in that case.

Your expression should be like this:

sed -i "s|STORAGE_ACCOUNT_KEY|EoKpaH0W/kqTv9awgIpQX5s+qQwGzXUSxMxhRjfSWG7SIUTWhut1OYQkNxhb3/9UKGf+g4tc3UaC0zKMTSrTNg==|g" test.xml

Note that the g modifier at the end of the command might not be necessary if you only have 1 string to replace per line.

Upvotes: 2

Related Questions