awk匹配/etc/hosts中不正确的主机名 [英] awk matching incorrect hostname in /etc/hosts

查看:119
本文介绍了awk匹配/etc/hosts中不正确的主机名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用该awk代码在/etc/hosts文件中挑选一个IP地址,尽管我可以强制它匹配正确的主机名,但是awk会首先选择一个几乎类似"的主机名.我已经对此进行了研究,但无法弄清.

I am using this awk code to pick out an IP address in the /etc/hosts file and although I can force it to match the correct hostname, awk will select an "almost like" hostname if it see's it first. I have researched this and I cannot figure it out.

sUSER=machine_005
ip=$(awk '/^[[:space:]]*($|#)/{next}/'$sUSER'/{print $1; exit}' /etc/hosts)

我知道第一部分寻找$或#,如果找到则调用下一行.最终公式中需要此功能.所需的另一个功能是在第一场比赛后停止. 我知道下一个/xxx/搜索该模式,如果找到,则将$ 1打印到$ ip.

I know the first part looks for $ or # and if found calls the next line. This feature is needed in the final formula. The other feature needed is to stop after the first match. I know that the next /xxx/ searches for the pattern and if found prints $1 to $ip.

这是我的主机文件的示例

Here is a sample of my hosts file

555.555.555.555 machine.005
222.222.222.222 machine_005

如果我$sUSER=machine_005 就像您期望的那样,$ip222.222.222.222.

if I $sUSER=machine_005 $ip is 222.222.222.222 just like you'd expect.

如果我$sUSER=machine.005 就像您期望的那样,$ip555.555.555.555

if I $sUSER=machine.005 $ip is 555.555.555.555 just like you'd expect

但是如果我的/etc/hosts是:

But if my /etc/hosts is:

222.222.222.222 machine_005
555.555.555.555 machine.005

然后,如果我$sUSER=machine_005 $ip222.222.222.222,就像您期望的那样.

Then if I $sUSER=machine_005 $ip is 222.222.222.222 just like you'd expect.

但是,如果我$sUSER=machine.005 $ip222.222.222.222,则它需要machine_005 ip地址.

However, if I $sUSER=machine.005 $ip is 222.222.222.222 It takes machine_005 ip address.

这可能是错误吗?还是故意的?

Could this be a bug? or is this on purpose?

谢谢.

你好.我想发布我的最后一行代码,以提供正确的输出.我感谢所有回应者的帮助和指导.我想发布最终代码,以防将来有人发现它有用.

Hello. I wanted to post my final line of code that provides the correct output. I appreciate all of the help and guidance from those who responded. I wanted to post the final code in case someone in the future can find it useful.

 ip=$(awk -v sUSER=$sUSER 'BEGIN{gsub(/\./,"\\.",sUSER)}match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/) && $0 ~ ("[^[:alpha:]]"sUSER"$") && $0 !~ /^$/ && $0 !~ /^#/{print $1}' /etc/hosts)

推荐答案

getent是用于从/etc/hosts(和其他配置数据库)中检索条目的工具:

getent is a tool meant to retrieve entries from /etc/hosts (and other config databases):

getent hosts "${USER}" | cut -d' ' -f1

这篇关于awk匹配/etc/hosts中不正确的主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆