Friday, January 26, 2024

[SOLVED] How to search & replace IP portion in a text file with IP:PORT format based on a preceding search key?

Issue

In my file, my script need to search marker_strings and then update the next text having IP:PORT format after it without changing its PORT value.

Here is an example scenario:

marker-a should use 600.0.0.100
marker-b should use 700.0.0.200

#sample file (before)

server marker-a 100.0.0.10:11648 check
server marker-b 100.0.0.11:11111 check
server marker-a 100.0.0.10:11648 check
server marker-b 100.0.0.11:11111 check

#sample file (after)

server marker-a 600.0.0.100:11648 check
server marker-b 700.0.0.200:11111 check
server marker-a 600.0.0.100:11648 check
server marker-b 700.0.0.200:11111 check

I've tried this based on other answers closest to this scenario and found this but nothing in output shows any changes.

sed -e '/^ *marker-a / s/ [^# ]/ 600.0.0.100/' input.txt
sed -e 's/^"marker-a" .*$/"marker-a 600.0.0.100"/' input.txt

Solution

Using any awk:

$ cat tst.awk
BEGIN {
    mark2ip["marker-a"] = "600.0.0.100"
    mark2ip["marker-b"] = "700.0.0.200"
}
$2 in mark2ip {
    sub(/[^:]+/,mark2ip[$2],$3)
}
{ print }

$ awk -f tst.awk file
server marker-a 600.0.0.100:11648 check
server marker-b 700.0.0.200:11111 check
server marker-a 600.0.0.100:11648 check
server marker-b 700.0.0.200:11111 check

The above assumes the new IP addresses don't contain &s (i.e. a backreference metachar) which is reasonable since it's an IP address. In general for a replacement that'll work for any characters just change sub(/[^:]+/,mark2ip[$2],$3) to sub(/[^:]+/,"",$3); $3=mark2ip[$2] $3.



Answered By - Ed Morton
Answer Checked By - Candace Johnson (WPSolving Volunteer)