IP address and country on the same line with AWK

I am looking for a one-line one which, based on a list of IP addresses, will add the country with which the IP address is based.

So, if I have it like input:

87.229.123.33
98.12.33.46
192.34.55.123

I would like to create this:

87.229.123.33 - GB
98.12.33.46 - DE
192.34.55.123 - US

I already have a script that returns the country for the IP address, but I need to glue it all together with awk until this waht I came up with:

$ get_ips | nawk '{ print $1; system("ip2country " $1) }'

All this is cool, but ip and country are not displayed on the same line, how can I combine the output of the system and ip on the same line?

If you have a better way to do this, I am open to suggestions.

+3
source share
3 answers

The correct single line solution in awk:

awk '{printf("%s - ", $1) ; system("ip2country \"" $1 "\"")}' < inputfile

However, I think it would be much faster if you use a python program that looks like this:

#!/usr/bin/python
# 'apt-get install python-geoip' if needed
import GeoIP
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
for line in file("ips.txt", "r"):
    line = line[:-1] # strip the last from the line
    print line, "-", gi.country_code_by_addr(line)

, geoip , . . python geoip. , awk 2 !

, , , , , geoip .

+2

printf :

{ printf("%s - ", $1); system("ip2country " $1); }
+5

I will answer with perl one-liner because I know this syntax better than awk. "Chomp" will cut a new line that bothers you.

get_ips | perl -ne 'chomp; print; print `ip2country $_`'
+1
source

Source: https://habr.com/ru/post/1708251/


All Articles