Search code examples
linuxapigeolocationxargs

xargs formation with ipinfo.io to get info in one line


The http://ipinfo.io getting started example for specific info tag like so:

cat ips.txt | xargs -I% curl -s http://ipinfo.io/%/org | paste -d"," ips.txt -

Return:

8.8.8.8,AS15169 Google Inc.
8.8.4.4,AS15169 Google Inc.
1.2.3.4,AS15169 Google Inc.

I want multiple pieces of info so I changed there example to:

cat ips.txt | xargs -I% curl -s http://ipinfo.io/%/city http://ipinfo.io/%/region | paste -d"," ips.txt - > ip_info.txt

Return:

156.221.17.167,Punjab
,Dol pri Ljubljani

how can I format my request to fit all the info relate to the IP in same line separated by a comma ',' like so:

156.221.17.167,Punjab,Dol pri Ljubljani

Solution

  • If you want multiple pieces of information you're better off getting it all in a single request and then using jq to pull out the pieces you want. Here's the full JSON output for an IP (see http://ipinfo.io/developers for more examples):

    $ curl ipinfo.io/8.8.8.8
    {
      "ip": "8.8.8.8",
      "hostname": "google-public-dns-a.google.com",
      "city": "Mountain View",
      "region": "California",
      "country": "US",
      "loc": "37.3860,-122.0838",
      "org": "AS15169 Google Inc.",
      "postal": "94035"
    }
    

    Then using jq to pull out the IP, city and country into CSV:

    $ curl -s ipinfo.io/8.8.8.8 | jq -r '[.ip, .city, .country] | @csv'
    "8.8.8.8","Mountain View","US"
    

    If we have a file with a bunch of IPs we can do it like this:

    $ cat ips.txt | xargs -I% curl -s http://ipinfo.io/%/json | jq -r '[.ip, .city, .country] | @csv'