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

本小妞迷上赌 提交于 2019-12-03 05:59:22

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")}'

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 need to include the sed code inside double quotes so that the used variable got expanded.

sed "s/\b\([0-9]\{1,3\}\.\)\{1,3\}[0-9]\{1,3\}\b/$IP/g" file

Add -i parameter to save the changes made. In basic sed \(..\) called capturing group. \{min,max\} called range quantifier.

Example:

$ IP='192.42.7.73'
$ echo '190.42.44.22   peep.strudel.com' | sed "s/\b\([0-9]\{1,3\}\.\)\{1,3\}[0-9]\{1,3\}\b/$IP/g"
192.42.7.73   peep.strudel.com
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!