Get JSON values using Shell script

1

I need to list the values of the number and url fields using the json shell script below:

[{
   "numero": "001",
   "local": "brasil",
   "url": "http://brasil.com.br",
   "ipv4": "10.10.0.1"
}]

I'm using this here: curl -s 'http://brasil.br/pub/retorno.json' | grep -Po '(?<="url": ")[^"]*' ,

but I just return the URL and would need:% number of%

    
asked by anonymous 04.10.2016 / 21:32

1 answer

0

Only with grep will not be able to get the string in the format you need ( numero - url ). With the help of the awk tool it is easier:

curl -s 'http://brasil.br/pub/retorno.json' | grep -Po '"(numero|url)": "\K[^"]*' | awk 'NR%2{ printf "%s - ", $0; next;}1'

Due to some limitations of lookbehind, such as accepting only fixed-length expressions, I made a slight modification to the regular expression. \K serves as a good alternative for lookbehind, since it is more flexible and still allows us to ignore everything that is before it, since it only makes what is after it is considered in the result of the expression.

awk is a very useful tool for filtering texts. We are using awk for every two lines, they are printed in linha_atual - linha_seguinte format.

05.10.2016 / 00:00