Thursday, February 3, 2022

[SOLVED] Replace ip:port to another ip:port using sed

Issue

I have nginx config file, where i have ip adress of my container. If i recreate container it will have the new ip, so i want to replace it.

I have .sh script:

#!/bin/bash
ip_new=$(sudo docker exec -ti pqf_ui_dev hostname -I) #to assign  container ip to this variable
sudo sed  "s~proxy_pass http[:]//[^ ][:]80*~proxy_pass http://$ip_new:80~"  -i /etc/nginx/sites- 
enabled/docker-pqf

so for example if my old ip:port was 172.17.0.1:80 and the new one is 172.17.0.2:80, my sed replace it like:

proxy_pass http://172.17.0.4 ^M:80

How i can change my script to replace ip without this ^M?


Solution

Use:

ip_new=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' pqf_ui_dev)

Instead of:

ip_new=$(sudo docker exec -ti pqf_ui_dev hostname -I)

And maybe you may like this sed:

sudo sed -E 's~(proxy_pass https?://)[^ :;]+(:?\d*)~\1'$ip_new'\2~' -i /etc/nginx/sites- enabled/docker-pqf

It is not perfect, but way more universal and without repeating searchtext like proto, host, port.



Answered By - Maxx Flow
Answer Checked By - Candace Johnson (WPSolving Volunteer)