Home > Back-end >  What's wrong with my sed command (BSD sed) regexp substitution
What's wrong with my sed command (BSD sed) regexp substitution

Time:08-04

I have a file called samconfig.toml

version = 0.1
~~~
parameter_overrides = "CognitoUserPoolName=\"aaa\" ApiAllowOrigin=\"'https://dev.xxxxxxxxx.amplifyapp.com'\" etc..
~~~

My sed command

sed -i '' -e "s#ApiAllowOrigin=\\\"'https.*com'\\\"#ApiAllowOrigin=\\\"'https://dev.yyyyyyyy.amplify.com'\\\"#g" ./samconfig.toml

It doesn't substitute the url. What's confusing about this, is that it contains all those single quotes, double quotes, back slashes..

I even checked with visualized regexp checker

enter image description here

CodePudding user response:

You may use this sed on macos:

sed -i.bak -E "s~(ApiAllowOrigin=\\\\\"'https://).*(\.com'\\\\\")~\1dev.yyyyyyyy.amplify\2~" file

cat file

version = 0.1
~~~
parameter_overrides = "CognitoUserPoolName=\"aaa\" ApiAllowOrigin=\"'https://dev.yyyyyyyy.amplify.com'\" etc..
~~~

Here:

  • When inside the double quotes you will need to use \\\\ to match a single \.
  • Note use or -E for extended regular expressions
  • We are using 2 capture groups to avoid repeating same pattern in match and substitution
  • Related