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

Non-greedy regex extraction from JSON with sed

Some JSON:

{"theSecret":"flhiusdh4543sdfasf34sdf+fsfs/sdf43454=","foo":{"bar":41,"something":"hello world","else":"hi","date":20230101,"qux":0,"digest":"sfhusdf234jkkjuiui23kjkj/SFDF34SDSFDS="}}

Prettified:

{
  "theSecret": "flhiusdh4543sdfasf34sdf+fsfs/sdf43454=",
  "foo": {
    "bar": 41,
    "something": "hello world",
    "else": "hi",
    "date": 20230101,
    "qux": 0,
    "digest": "sfhusdf234jkkjuiui23kjkj/SFDF34SDSFDS="
  }
}

I want the value of the theSecret key.

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

I tried this:

$ echo "$json" | sed -nE 's/.*theSecret":"(.*)".*/\1/p'    # (.*?) doesn't work

Which gives:

flhiusdh4543................4SDSFDS=

i.e. from theSecret until the end of digest. That’s because sed lacks non-greedy quantifiers, so .*? doesn’t work.

How can I do this?

(This is in an alpine container, which has sed, grep and awk. jq and perl are unavailable.)

>Solution :

Instead of using a non-greedy quantifier, use a pattern that doesn’t match the terminating ".

$ echo "$json" | sed -nE 's/.*theSecret":"([^"]*)".*/\1/p'    # (.*?) doesn't work
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