此题关键在于正则匹配

0-255数字匹配

  • 0-99匹配表达式:[1-9]?[0-9]
  • 100-199匹配表达式:1[0-9]{2}
  • 200-249匹配表达式:2[0-4][0-9]
  • 250-255匹配表达式:25[0-4]

0-255 匹配表达式:[1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-4]

正确ip的匹配表达式:^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-4])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-4])$

awk方式

awk '{if($0~/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/){print "yes"}else if($0~/(^[0-9]+\.){3}([0-9]+)$/){print "no"}else print "error"}' 

while read line方式

#!/bin/bash
ip_re='^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$'
while read line;do
    if [[ $line =~ ^([0-9]+\.){3}([0-9]+)$ ]];then
        if [[ $line =~ $ip_re ]];then
            echo 'yes'
        else
            echo 'no'
        fi
    else
        echo 'error'
    fi
done<./nowcoder.txt