Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to output city by IP address to stdout?

I have a list of IP addresses in the ip.txt file (there are a lot of them).
I used ipinfo.io services to search data by IP and sed to cut out only the city.

#!/bin/bash
while IFS= read -r ip; do
    curl ipinfo.io/$ip >> test.txt
    sed -i '/city/!d' test.txt
    cat /dev/null > test.txt
done < ip.txt

However, the script doesn`t display the city in a loop over all IPs (only works on individual data), but displays a lot of unnecessary information.
For example, for the following IPs (generated automatically):

97.108.178.66
98.10.198.56
201.12.36.90

My output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   332  100   332    0     0   2145      0 --:--:-- --:--:-- --:--:--  2155
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   323  100   323    0     0   1345      0 --:--:-- --:--:-- --:--:--  1340
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   266  100   266    0     0   1426      0 --:--:-- --:--:-- --:--:--  1430

Required output:

  "city": "Toronto",
  "city": "Rochester",
  "city": "Rio de Janeiro",

How can this be done?

>Solution :

It’s not clear whether you’re trying to capture the cities in a text file or display them. If you want them stored, don’t overwrite the results.

$ cat tmp 
#!/bin/bash
while IFS= read -r ip; do
    curl ipinfo.io/$ip >> test.txt 2>/dev/null
    sed -i '/city/!d' test.txt
done < ip.txt
$ cat ip.txt 
97.108.178.66
98.10.198.56
201.12.36.90
$ ./tmp 
$ cat test.txt 
  "city": "Toronto",
  "city": "Rochester",
  "city": "Rio de Janeiro",
$ 

If you just want to see them on screen:

$ cat tmp 
#!/bin/bash
while IFS= read -r ip; do
    curl ipinfo.io/$ip 2>&1 | sed  '/city/!d'
done < ip.txt
$ ./tmp 
  "city": "Toronto",
  "city": "Rochester",
  "city": "Rio de Janeiro",
$ 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading