0

I'm trying to use sed to replace a text with a variable value.

The variable regex holds a regular expression as a value:

regex=^/v(\d+)/stats.(xml|json)(.*)$

The sed command I'm trying looks like this:

sed 's/?PATH_REGEX/'"$regex"'/g' <<<"$templateEscapedForSed"

The $templateEscapedForSed variable holds a simple template shown below. In this case I'm trying to replace '?PATH_REGEX' with a value of the $regex variable.

$templateEscapedForSed holds the following:

location ~* ?PATH_REGEX {
            rewrite ?PATH_REGEX ?URL break;
    }

When the value of the $regex is a simple text without any special characters (e.g. "test") this sed command works ok:

location ~* test {\
        rewrite test ?URL break;\
}

However when the regex variable holds the regular expression mentioned above I'm getting an error:

sed: -e expression #1, char 17: unknown option to `s'

I suspect the value of the regex variable is being interpreted and thus causing an error.

What I want to get in the result is:

location ~* ^/v(\d+)/stats.(xml|json)(.*)$ {
            rewrite ^/v(\d+)/stats.(xml|json)(.*)$ ?URL break;
    }

Is there a way to just insert the value of the regex variable 'as is'?

1urk3r
  • 3
  • 1
  • Does https://stackoverflow.com/questions/407523/escape-a-string-for-a-sed-replace-pattern answer your uestion? – KamilCuk Sep 28 '22 at 06:47

1 Answers1

0

There's conflict due to slashes being present in the value of the regex variable. However, sed allows its s command to use a different separator. The first character after the s command becomes the separator. For example, all these are equivalent:

s/.../.../g
s|...|...|g
s;...;...;g

So, use a delimiter that's not part of the string used as a replacement:

sed "s;?PATH_REGEX;$regex;g" <<<"$templateEscapedForSed"
Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202