0

Now I want to use sed to replace the url from a file, this is the original file:

server {
    listen       80;
    server_name  localhost;
location /api/test {
    proxy_connect_timeout 3000;
    proxy_send_timeout 3000;
    proxy_read_timeout 3000;
    send_timeout 3000;
    client_max_body_size 10M;
    client_body_buffer_size 100M;

proxy_pass:www.baidu.com }

location /api/demo {
    proxy_connect_timeout 3000;
    proxy_send_timeout 3000;
    proxy_read_timeout 3000;
    send_timeout 3000;
    client_max_body_size 10M;
    client_body_buffer_size 100M;

proxy_pass:www.google.com } }

and this is the replace shell script:

#!/usr/bin/env bash

set -u

set -e

set -x

echo "please input url1:"

read URL1

echo "$URL1"

echo "plase input url2:"

read URL2

echo "$URL2"

sed -E -in-place "12s/.proxy_pass./proxy_pass:$URL1/" nginx.conf

sed -E -in-place "22s/.proxy_pass./proxy_pass:$URL2/" nginx.conf

this script works fine, but when I input the url with http like this format: http::/www.google.com, the script shows error like this:

+ sed -E -in-place '12s?.*proxy\_pass.*/proxy\_pass:http::/www.google.com?' nginx.conf
sed: 1: "12s?.*proxy\_pass.*/pro ...": unterminated substitute in regular expression

what should I do to make the sed works with special charactors?

Dolphin
  • 609

1 Answers1

2

You can use a different delimiter to the s command instead of /:

sed -E -in-place "12s|.*proxy_pass.*|proxy_pass:$URL1|" nginx.conf

assuming your URL can't contain |. Beware that the URL must still not contain &, which is a legal URL character, but has a special meaning in sed replacements.

I also removed the backslashes before the underscores, because \_ is undefined and could produce strange results in some sed implementations.

Finally, you may consider adding a semicolon after the URLs in the replacement, so the URLs do not need to contain them:

sed -E -in-place "12s|.*proxy_pass.*|proxy_pass:$URL1;|" nginx.conf
Philippos
  • 13,453