[Shell Tips] IPv4 address 判斷

IPv4 address 判斷

找出/etc/hosts 中含有IP 的文字列
grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' /etc/hosts

取出/etc/hosts 中含有IP 的部分
grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' /etc/hosts

用bash判斷字串是否為IPV4
if [ ` echo $ip | grep -E '^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'  | grep -o "\." | wc -l` -eq 3 ];
then 
    ipv4=true
else 
    ipv4=false
fi

參考來源:

  1. What regular expression can I use to match an IP address?
  2. Shell 搭配正規式來檢測一字串是否為IPv4 格式之IP
This entry was posted in shell script and tagged . Bookmark the permalink.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *