Sometimes you need to swap an IP address out of a file. Maybe you are moving a server to a new host, updating a config, or just tired of grepping through logs to find the old address. Whatever the reason, sed makes it trivial.

The trick is matching the dotted-decimal pattern. An IP address is four groups of numbers separated by dots, so the regex needs to capture that structure. Here is the one-liner:

sed 's/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/NEW.IP.ADDRESS/g' /SourceFilename > /DestinationFilename

A few things to watch out for. The dots in the regex are unescaped, which means they match any character. That is fine for most cases, but it also means the pattern will match something like 999x999y999z999. If you want to be stricter, escape the dots: \.. The \{1,3\} quantifiers match one to three digits per octet, which covers every valid IP without being overly restrictive.

The g flag at the end is important. Without it, sed replaces only the first match on each line. If your file has the same IP repeated multiple times, you want the global flag to catch them all.

I tend to write the output to a new file rather than editing in place, just so I can sanity-check the result before overwriting anything. Once I am happy with the output, I swap the files over manually. It is two extra steps, but it saves the occasional panic when a regex goes wrong.