Get JSON values using Shell script

Asked

Viewed 421 times

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 wearing this here: curl -s 'http://brasil.br/pub/retorno.json' | grep -Po '(?<="url": ")[^"]*',

but returns only the URL and would need: number - url

  • Have you looked at this tool: https://stedolan.github.io/jq/ ?

1 answer

0


Only with the grep you won’t get the string in the format you need (numero - url). With the help of the tool awk gets 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 the lookbehind, such as accepting only fixed-size expressions, I made a small modification to the regular expression. The \K serves as a good alternative to the lookbehind, as it is more flexible and still allows us to ignore everything that is before it, since it makes only what is after it is considered in the result of the expression.

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

  • Worked perfectly !!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.