简体   繁体   中英

How to replace IP in zone file with sed

I am trying to use sed to replace an IP in a zone file for a specific record. Using the below example I want to replace the IP for server1. I am having problems with just replacing the IP and not the entire line. Can anyone help please as I am at a total loss with sed at the moment.

$ORIGIN example.com
$TTL 86400
@     IN     SOA    dns1.example.com.     hostmaster.example.com. (
                    2001062501 ; serial
                    21600      ; refresh after 6 hours
                    3600       ; retry after 1 hour
                    604800     ; expire after 1 week
                    86400 )    ; minimum TTL of 1 day

      IN     NS     dns1.example.com.
      IN     NS     dns2.example.com.

      IN     MX     10     mail.example.com.
      IN     MX     20     mail2.example.com.

             IN     A       10.0.1.5

server1      IN     A       10.0.1.5
server2      IN     A       10.0.1.7
dns1         IN     A       10.0.1.2
dns2         IN     A       10.0.1.3

You can use

IP="1.2.3.4"
sed "/^server1/s/[^[:space:]]\+$/$IP/" file

If you are fine with the changes, you can pass -i to change the file in in place :

IP="1.2.3.4"
sed -i "/^server1/s/[^[:space:]]\+$/$IP/" file

Btw, if there may space occur at the end of the line I would suggest this:

sed "/^server1/s/[^[:space:]]\+[[:space:]]\{0,\}$/$IP/" file
sed -r "s/^(server1.*)([0-9]+[.][0-9]+[.][0-9]+.[0-9]+[ ]*)$/\1$NEWIP/" my_file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM