SED:在hosts文件替换IP,使用主机名模式 [英] sed: replace ip in hosts file, using hostname as pattern
问题描述
我学习sed的,但对我来说很困难的理解。
I'm learning about sed but it is very difficult to me understand it.
我有一个动态IP的ADSL等等,我希望把当前的IP主机上的文件。
I have adsl with dynamic ip so and i want to put current ip on hosts file.
这下面的脚本只是告诉我目前的广域网IP地址,并没有更多的:
This following script just tells me the current wan ip address and no more:
IP=$(dig +short myip.opendns.com @resolver1.opendns.com)
echo $IP
结果:
192.42.7.73
所以,我对主机的符合旧的IP地址文件:
So, i have a line on hosts file with the old ip address:
190.42.44.22 peep.strudel.com
和我想更新这样的主机文件:
and i want to update host file like this:
192.42.7.73 peep.strudel.com
我该怎么办呢?我想我可以使用主机名作为模式...
How can i do it? I think i can use the hostname as pattern...
这样做的原因是因为我的服务器是我的路由器的客户,所以它访问网络直通其网关而不是直接。和Postfix总是登录我说:未知[X.X.X.X]连接(其中X.X.X.X是我的广域网IP!),它无法解析IP地址。我想,也许,如果我指定这个与我的FQDN主机/域有关,在hosts文件,将更好地工作。
The reason of doing this is because my server is a client of my router, so it access the internet thru its gateway and not directly. And postfix always is logging me that "connect from unknown [x.x.x.x]" (where x.x.x.x is my wan ip!) and it can't resolve that ip. I think that maybe if i specify this relating with my fqdn host/domain, on hosts file it will works better.
谢谢
塞尔吉奥。
Thanks Sergio.
推荐答案
使用的sed
sed -r "s/^ *[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+( +peep.strudel.com)/$IP\1/"
。 [0-9] + \\。
发现1个或多个数字与此模式匹配的所有行然后连续4次模式 peep.strudel.com
周围的图案.The括号 peep.strudel.com
另存为 \\ 1
然后更换整个彭定康与你的变量,并为新的IP。
.
[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.
另一种方法:而不是保存模式来命名的IP变量,可以执行sed命令行里的命令行来获得新的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/"
使用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")}'
这篇关于SED:在hosts文件替换IP,使用主机名模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!