for、if之过滤合法IP地址
1 #!/bin/bash
2 #判断合法IP脚本
3 #Autor:lyz(E-mail:liyzmx@163.com)
4
5 grep "^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$" /root/sh/ip.txt >ip_test.txt
6 #先通过正则将IP进行粗过滤,把明显不符合的过滤掉
7
8 echo "" >ip_ok.txt
9 #清空保存数据的文件
10
11 for i in $(cat /root/sh/ip_test.txt)
12 do
13 first=$(echo $i | cut -d "." -f 1)
14 second=$(echo $i | cut -d "." -f 2)
15 third=$(echo $i | cut -d "." -f 3)
16 fourth=$(echo $i | cut -d "." -f 4)
17 #分别把IP地址的四个数值分别赋予四个变量
18
19 if [ "$first" -lt 1 -o "$first" -gt 255 ]
20 #如果第一个数值大于1或大于255
21 then
22 continue
23 #退出本次循环
24 fi
25
26 if [ "$second" -lt 0 -o "$second" -gt 255 ]
27 then
28 continue
29 fi
30
31 if [ "$third" -lt 0 -o "$third" -gt 255 ]
32 then
33 continue
34 fi
35
36 if [ "$fourth" -lt 0 -o "$fourth" -gt 255 ]
37 then
38 continue
39 fi
40
41 echo "$i" >>/root/sh/ip_ok.txt
42 #把合法IP地址写入/root/sh/ip_ok.txt文件
43 done
44
45 rm -rf /root/sh/ip_test.txt
46 #删除临时文件