如何查找字符串并替换 { ... } 之间的某些字符串?

问题描述 投票:0回答:1

您只需更改/test/v2.0.0块中的端口:

server {
    location /test/v2.0.3 {
        modsecurity on;
        proxy_pass http://10.1.0.6:3000;
    }
    location /test/v2.0.0 {
        modsecurity on;
        proxy_pass http://10.1.0.6:3000;
    }
}

sed '0,/:[0-9].*;/{s/:[0-9].*;/:5555;/}' test.nginx
- 改变第一场比赛

sed '/.*location.*\/test\/v2.0.0\/.*:[0-9].*;/{s/:[0-9].*;/:5555;/}' test.nginx
- 不会改变任何东西

sed 's/.*location.*\/test\/v2.0.0\/.*:[0-9].*;/:5555;/' test.nginx
- 不会改变任何东西

附注:

任务听起来像什么: 找到位置

/test/v2.0.0.0
前面有除
#
之外的任何字符,选择括号
{
}
中的所有内容,找到端口字符串
:3000
;之间,替换为指定的。

输出:

server {
    location /test/v2.0.3 {
        modsecurity on;
        proxy_pass http://10.1.0.6:3000;
    }
    location /test/v2.0.0 {
        modsecurity on;
        proxy_pass http://10.1.0.6:5555;
    }
}
awk sed
1个回答
0
投票

您可以使用以下

awk
来实现您的结果。

awk '
/location \/test\/v2.0.0/ {flag=1}
flag && /proxy_pass/ {sub(/:[0-9]+;/, ":5555;")}
/}/ {flag=0}
{print}
' your_file

该命令将:

  1. 当找到包含位置
    flag
    的行时,设置
    /test/v2.0.0
  2. 如果设置了标志并且该行包含
    proxy_pass
    ,它将用
    5555
    替换端口号。
  3. 当找到右大括号(
    }
    )时,
    flag
    将被取消设置,并且将打印每一行。
© www.soinside.com 2019 - 2024. All rights reserved.