hansfrans hansfrans - 5 months ago 21x
Bash Question

Read file that contains IPs and write countrycode into new IP.txt file

I need help with a script that is looking into a file (serverlist.txt) for ip:port.

The serverlist.txt contains rumber numbers of IP:port.


The script should cut the port and then request the countrycode with geoiplookup. When its finished, for every ip there should be the countrycode in a new own file like this:



This is the code i have till now:


cat serverlist.txt |while read $socket; do cut -f1 -d":">ip.txt; done;
cat ip.txt | while read ip; do geoiplookup $ip | awk -v FS="(GeoIP Country Edition: |,)" '{print $2}'>>countrycode.txt ; done;

I can get the ips and the countrycode. But i dont know how to match them together into the new files.
Thanks for any help. ;)


Let's not create an intermediary ip.txt file and just loop through the contents in serverlist.txt.

By setting the internal field separator (IFS) to :, you can extract both ip and port. Then, run geoiplookup against it, pipe to awk as you are doing and store the output in a variable $country.

Finally, write it into a file named after the ip:

while IFS=":" read ip port; do
    country=$(geoiplookup "$ip" | awk -v FS="(GeoIP Country Edition: |,)" '{print $2}')
    printf "$country\n" >> $ip:$port.txt
done < serverlist.txt

This is very similar to what you were doing, you only needed to refer to the variable $ip to store the name.

cat ip.txt | while read ip; do  ... >> $ip.txt ; done;
#                                      ^^^

Note I am using the syntax while read; do ... done < file instead of cat file | while ..., so that you don't open a subshell and all the variables defined within the loop are available outside it.