jus*_*ing 2 regex linux dns bash hosts
需要使用已知主机名grep/etc/hosts,然后从/ etc/hosts捕获主机名的ip地址.
我不是程序员,也不知道怎么做.我对正则表达式的经验非常有限,但认为这可能会以某种方式起作用.我没有使用DNS,只使用/ etc/hosts文件进行管理.
我需要使用已知的主机名grep/etc/hosts文件,然后捕获hosts条目的IP地址.主机文件是标准格式:
请帮忙!
#
维护网络
192.168.80.192 testsrv01-maint
192.168.80.193 testsrv02-maint
192.168.80.194 testsrv03-maint
Run Code Online (Sandbox Code Playgroud)
#
熄灯网络
192.168.120.192 testsrv01-ilo
192.168.120.193 testsrv02-ilo
192.168.120.194 testsrv03-ilo
Run Code Online (Sandbox Code Playgroud)
#
主要数据网络
192.168.150.192 testsrv01-pri
192.168.150.193 testsrv02-pri
192.168.150.194 testsrv03-pri
Run Code Online (Sandbox Code Playgroud)
#
二级数据网络
192.168.200.192 testsrv01-sec
192.168.200.193 testsrv02-sec
192.168.200.194 testsrv03-sec
Run Code Online (Sandbox Code Playgroud)
我需要能够将每台机器的ip地址和完整主机名条目捕获到我可以使用的变量中.例如,运行文件寻找匹配"testsrv01*",并捕获该搜索的所有IP地址和名称.然后同样为"testsrv02*",依此类推.
bis*_*hop 10
简单回答
ip=$(grep 'www.example.com' /etc/hosts | awk '{print $1}')
更好的答案 简单的答案返回所有匹配的IP,甚至是评论行上的IP.您可能只想要第一个非评论匹配,在这种情况下只需使用awk:
ip=$(awk '/^[[:space:]]*($|#)/{next} /www.example.com/{print $1; exit}' /etc/hosts)
另一件事如果你在某个时候关心解决www.example.com你的系统是否配置为使用主机,dns等,那么考虑一下鲜为人知的getent
命令:
ip=$(getent hosts 'www.example.com' | awk '{print $1}')
编辑以响应更新
$ cat script.sh
#!/bin/bash
host_to_find=${1:?"Please tell me what host you want to find"}
while read ip host; do
echo "IP=[$ip] and host=[$host]"
done < <(awk "/^[[:space:]]*($|#)/{next} /$host_to_find/{print \$1 \" \" \$2}" /etc/hosts)
$ ./script.sh testsrv01
IP=[192.168.80.192] and host=[testsrv01-maint]
IP=[192.168.120.192] and host=[testsrv01-ilo]
IP=[192.168.150.192] and host=[testsrv01-pri]
IP=[192.168.200.192] and host=[testsrv01-sec]
Run Code Online (Sandbox Code Playgroud)