代码之家  ›  专栏  ›  技术社区  ›  duckyflip

IP地址和国家/地区与AWK位于同一行

  •  3
  • duckyflip  · 技术社区  · 15 年前

    我正在寻找一个基于IP列表的单行线,它将附加IP所在国

    因此,如果我将此作为输入:

    87.229.123.33
    98.12.33.46
    192.34.55.123
    

    87.229.123.33 - GB
    98.12.33.46 - DE
    192.34.55.123 - US
    

    我已经有一个脚本返回IP的国家,但我需要用awk将其粘在一起,到目前为止,这是我想到的:

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

    如果你有更好的方法,我愿意接受建议。

    3 回复  |  直到 15 年前
        1
  •  5
  •   hvintus    15 年前

    你可以用 printf

    { printf("%s - ", $1); system("ip2country " $1); }
    
        2
  •  2
  •   Floyd    11 年前

    awk中合适的单衬里解决方案为:

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

    #!/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 binding for geoip

    我不知道你需要处理多少条目,但是如果它的大部分,你应该考虑一些不叉和保持GEOIP数据库在内存中的东西。

        3
  •  1
  •   amarillion    15 年前

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