Loading...

sed: replace ip in hosts file, using hostname as pattern

Answer #1 100 %

using sed

sed -r "s/^ *[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+( +peep.strudel.com)/$IP\1/"

. [0-9]+\. find all lines that matches 1 or more digits with this pattern 4 consecutive times then pattern peep.strudel.com .The parenthesis around the pattern peep.strudel.com save it as \1 then replace the whole patten with your variable and your new ip.

another approach:instead of saving pattern to a variable named IP, you can execute your command line inside sed command line to get the new IP .

   sed -r "s/^ *[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+( +peep.strudel.com)/$(dig +short myip.opendns.com @resolver1.opendns.com)\1/"

using gawk

gawk -v IP=$IP '/ *[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+( +peep.strudel.com).*/{print gensub(/ *[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+( +peep.strudel.com)/,IP"\\1","g")}'
Answer #2 100 %

You can use a simple shell script:

#! /bin/bash

IP=$(dig +short myip.opendns.com @resolver1.opendns.com)

HOST="peep.strudel.com"

sed -i "/$HOST/ s/.*/$IP\t$HOST/g" /etc/hosts

Explanation:

sed -i "/$HOST/ s/.*/$IP\t$HOST/g" /etc/hosts means in the line which contains $HOST replace everything .* by $IP tab $HOST.

You’ll also like:


© 2022 CodeForDev.com -