1

I want to use grep to get a number from a JSON file For example, I want to get the 1.0872 from this:

{"base":"EUR","date":"2016-03-01","rates":{"USD":1.0872}}

Using

grep "USD" rates

gives out the whole line

{"base":"EUR","date":"2016-03-01","rates":{"USD":1.0872}}

I just want to display 1.0872.

I tried using a regex but it doesn't work (probably an error on my part since I've never done this before):

grep -oP '(?<="USD"\:)\w+' file
Curti21
  • 13
  • 4
  • For a start \w+ won't give you 1.0872 because '.' is not classed in \w. try changing it to [\d\.]+. It won't fix the whole problem but it should help. – EDD Mar 01 '16 at 23:02
  • Check [this demo](http://ideone.com/Mk5Ctx), try `grep -oP '(?<="USD":)[\d.]+' file`. Or `grep -oP '(?<="USD":)\d*\.?\d+' file`. – Wiktor Stribiżew Mar 01 '16 at 23:07

1 Answers1

0

For "normal" integers and float values, you may use

grep -oP '(?<="USD":)\d+(?:\.\d+)?' file

If your numbers can have no integer part and can start with a ., use

grep -oP '(?<="USD":)\d*\.?\d+' file

An optional -:

grep -oP '(?<="USD":)-?\d*\.?\d+' file

See IDEONE demo

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563