Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find string and replace some string between { … }?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

  1. Set a flag when the line containing location /test/v2.0.0 is found.
  2. If the flag is set and the line contains proxy_pass, it will substitute the port number with 5555.
  3. When the closing brace(}) is found, the flag is unset and each line will be printed.

demo here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading