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 《加州旅館》


