Bash – How to Extract Data from URL

bash

How can I extract the ip address and the country and put them individual in a string without any quotes or any other characters which are present in the text by using the next command:

info_ip=`wget --tries=1 --timeout=10 -qO- http://ipinfo.io/?callback=callback; echo`

$ip = ?

$country = ?

Best Answer

You can use awk to catch the ip and country and save into an array:

IFS=$'\n'
IP_country=( $(awk -F'[:"]' '/ip/ || /country/{ print $5}' <<<"$( wget ... )") )

Then first element is ip and the next is country:

printf '%s\n' "${IP_country[0]}"
1.2.3.4
printf '%s\n' "${IP_country[1]}"
IR

Or to print all elements:

printf '%s\n' "${IP_country[@]}"
1.2.3.4
IR

Future reading:

Related Question