Sample Header Ad - 728x90

Loop ip list through geoiplookup and delete lines that do not match criteria

1 vote
3 answers
108 views
Thanks in advance for any ideas you present. My current project has me trying to loop a file containing a list of 1000's of IP addresses through geoiplookup and piping it to sed to delete all lines that do not match criteria. The list is just a list of ip addresses:
1.2.3.4
5.6.7.8
9.10.11.12
.
.
.
I then run geoiplookup ip.ad.dre.ss as root, and get:
[root@system ipset]# geoiplookup 4.2.2.2
GeoIP Country Edition: US, United States
if the IP is within the US. My goal is to delete all lines from the file, if their IP is not in the US. What I tried is not working:
#!/bin/bash

for ip in $(cat /tmp/iplist.txt); do
     geoiplookup $ip | sed '/GeoIP Country Edition: US, United States/!d'
done
Any suggestions? Recommendations of another approach would be greatly appreciated. @terdon Sorry I haven't updated sooner, I have been busy. Adding either to this question or comment messes up formatting of text. Sorry newbie to Stack...let me figure this out. OK, update. after changing up and running @terdon first code:
#!/bin/bash

while read ip; do
  if ! geoiplookup "$ip" | grep -q ': US, United States$'; then
    sed -i "/^$ip$/d" /tmp/iplist.txt
  fi
done < /tmp/iplist.txt
it runs without error but non-US ip address still are in list. I had been using the last example with the declare -a badLines
scripts#geoiplookup 172.168.155.63
GeoIP Country Edition: GB, United Kingdom

scripts#grep 172.168.155.63 /tmp/iplist.txt
172.168.155.63
Once I figure out how to get copy and paste to work right into the question here I will update. @Ed Morton Both examples produce same error at the "done" line, line 7 in one and line 9 in the other.
./filter_ips.sh: line 7: syntax error near unexpected token `done'
./filter_ips.sh: line 7: `   done < "${@:--}"'
@Miri B They run through but there are still non-US ip addresses in the list.
Asked by user711431
Feb 10, 2025, 12:41 PM
Last activity: Feb 11, 2025, 10:49 PM