8 种方法找到 IP 对应的唯一hostname
- 2019 年 12 月 12 日
- 筆記
问题
/etc/hosts文件内容为:
[root@oracle ~]# cat /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 oracle ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.8.111 bk.com 192.168.8.112 pbk.com 192.168.8.123 hbck.com
如何用shell脚本实现在输入IP后找到/etc/hosts里对应的唯一的hostname呢?
这个问题看似简单,但如果你不熟悉多种方法可能会很吃亏,所以一定要学会这个,或许某天可以帮你大忙。
方法有很多,这里只介绍简单易掌握的8种。
grep 过滤
法一
[root@oracle ~]# cat Query_Host.sh #!/bin/bash echo "Please input ip address:" read ip [ -n "`grep "$ip " /etc/hosts`" ] && echo "The hostname is: (`grep "$ip " /etc/hosts |awk '{print $2}'`)" || echo "The ip address is invalid"

awk 精确匹配
法一
[root@oracle ~]# cat Query_Host.sh #!/bin/bash if [ $# -ne 1 ] then echo "{Usage:sh $0 IP}" exit 1 fi flag=0 exec < /etc/hosts while read line do if [ "$1" = "`echo $line|awk '{print $1}'`" ] then flag=1 echo "The ***("$1")*** opposite hostname is ***("`echo $line|awk '{print $2}'`")***" break; fi done [ $flag -eq 0 ] && echo " Sorrry, dont find ($1) opposite hostname!"

法二
[root@oracle ~]# cat Query_Host.sh #!/bin/bash awk 'BEGIN {a="'$1'"} {if($1==a) print $2; }' /etc/hosts

法三
[root@oracle ~]# cat Query_Host.sh #!/bin/bash awk '{if($1=="'$1'") print $2}' /etc/hosts

法四
[root@oracle ~]# cat Query_Host.sh #!/bin/bash awk '{if($1~/'$1'$/) print $2}' /etc/hosts

法五
[root@oracle ~]# cat Query_Host.sh #!/bin/bash #ip=$1 awk -v ip="$1" '$1 == ip{print $2}' /etc/hosts

法六
[root@oracle ~]# cat Query_Host.sh #!/bin/bash awk '$1 == "'$1'" {print $2}' /etc/hosts

awk 过滤
方法一
[root@oracle ~]# cat Query_Host.sh #!/bin/bash awk '/'"${1} "'/''{print $2}' /etc/hosts

有人翩翩求记住,有人起舞求忘记。from 《加州旅馆》


