写一个脚本统计文件nowcoder.txt中的每一行是否是正确的IP地址。
如果是正确的IP地址输出:yes
如果是错误的IP地址,且是四段号码的话输出:no,否则的话输出:error
假设nowcoder.txt内容如下:
192.168.1.1
192.168.1.0
300.0.0.0
123
你的脚本应该输出:
yesyesnoerror
192.168.1.1
192.168.1.0
300.0.0.0
123
yesyesnoerror
192.168.1.1 192.168.1.0 300.0.0.0 123
yes yes no error
此题关键在于正则匹配
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])$河边小石子题解如下:
#!/bin/bash
ip_yes='^(([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])$'
ip_no='^([0-9]+\.){3}([0-9]+)$'
while read line;
do
if [[ $line =~ $ip_no ]];then #注意=~
if [[ $line =~ $ip_yes ]];then
echo "yes"
else
echo "no"
fi
else
echo "error"
fi
done<./nowcoder.txt
awk -F "." '{ aa = 0;
if( NF == 4 )
{
aa = 1;
for(i = 1;i <= NF;i++)
{
if( $i > 255)
{
aa = 2;
}
}
}
if( aa==0 ){printf "error\n";}
if( aa==1 ){printf "yes\n";}
if( aa==2 ){printf "no\n";}
}'
while read line; do
num=$(echo $line|awk -F"." '{print NF}')
if [ $num -ne 4 ]; then
echo "error"
continue
fi
flag=true
for ip in $(echo $line|awk -F. '{for(i=1;i<=NF;i++) print $i}'); do
if [ $ip -gt 255 -o $ip -lt 0 ]; then
flag=false
fi
done
if [ $flag = true ]; then
echo "yes"
else
echo "no"
fi
done < nowcoder.txt while read ip
do
if [[ $ip =~ ^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[09][0-9]|[1-9][0-9]|[0-9])$ ]]; then
echo "yes"
elif [[ $ip =~ [0-9].[0-9].[0-9].[0-9] ]]; then
echo "no"
else
echo "error"
fi
done < nowcoder.txt