You only need to change the port in the /test/v2.0.0 block:
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
– changes the first match
sed '/.*location.*\/test\/v2.0.0\/.*:[0-9].*;/{s/:[0-9].*;/:5555;/}' test.nginx
– doesn’t change anything
sed 's/.*location.*\/test\/v2.0.0\/.*:[0-9].*;/:5555;/' test.nginx
– doesn’t change anything
P.S.:
What the task sounds like:
Find location /test/v2.0.0.0 preceded by any character except #, select everything in the brackets { }, find the port string :3000; between them, replace it with the specified one.
Output:
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;
}
}
>Solution :
You can use the below awk to achieve your result.
awk '
/location \/test\/v2.0.0/ {flag=1}
flag && /proxy_pass/ {sub(/:[0-9]+;/, ":5555;")}
/}/ {flag=0}
{print}
' your_file
The command will:
- Set a
flagwhen the line containing location/test/v2.0.0is found. - If the flag is set and the line contains
proxy_pass, it will substitute the port number with5555. - When the closing brace(
}) is found, theflagis unset and each line will be printed.