I have to sort IP addresses into classes, so I can block entire class in myfirewall. It works fine when I try to do for /24 class, but not so well when do for /16 class. I have a list of IPs in the txt file, from which I'd like to sort
for IPBL in `cat /tmp/IPs`; do
CT=`grep -c ${IPBL%.[0-9]*} /tmp/IPs`
if [ "$CT" -gt "10" ]; then
echo "$IPBL ${IPBL%.[0-9]*}.0/24 $CT" >>/tmp/spam.lst
fi
done
cat /tmp/spam.lst |sort -n
So this works fine and prints me out all ip that have more than 10 matches is C class.
for IPBL in `cat /tmp/IPs`; do
CT=`grep -c ${IPBL%.[0-9]*.[0-9]*} /tmp/IPs`
if [ "$CT" -gt "10" ]; then
echo "$IPBL ${IPBL%.[0-9]*.[0-9]*}.0.0/16 $CT" >>/tmp/spam.lst
fi
done
cat /tmp/spam.lst |sort -n
So in this example in gets most of the matches OK, but some would grep more, for example.
- ip
8.6.X.Xwould match18.6.X.X,168.6.X.Xetc.
I tried to place ^${IPBL%.[0-9]*.[0-9]*} in the grep to match beginning of the line, but didn't help, also not
grep -E -c "${IPBL%.[0-9]{1,3}.[0-9]{1,3}}" /tmp/IPs
to have specific number of digits match within ip numbers, and neither placing ^ in front of the string.
What is the most efficient way to pull out exact matches?
File /tmp/IPs is big, but doing B mask grep matches all of the following IP numbers. Correct would be with only 1 match (line 2).
#IPBL=8.6.144.6
#grep ${IPBL%.[0-9]*.[0-9]*} /tmp/IPs
5.188.62.76
8.6.144.6
39.48.63.128
49.178.61.44
68.61.98.98
73.121.228.65
78.128.60.44
81.68.68.194
86.185.248.61
103.129.178.69
108.61.115.213
108.61.199.100
138.68.224.206
138.68.235.36
142.4.218.69
148.63.196.97
148.64.121.254
148.66.129.250
148.66.130.114
149.202.8.66
173.228.198.65
174.251.128.60
176.78.65.246
176.9.208.67
178.128.68.121
178.62.67.41
178.63.146.46
212.48.66.224
/tmp/IPsit is difficult to understand. Please specify (an excerpt of) the original/tmp/IPsalong with the desired output.