3

In the Bash I saved response data into a variable.

The result looks like this:

{"token_type":"Bearer","access_token":"022-8baa5324-f57b-445d-c5ec-821c63a5fd35","expires_in":3600,"scope":"any-website.com"}

Now I want to extract the value of the access token into an other var.

In Linux I solved that in this way and it works:

echo "$response_json" | grep -oP '(?<="access_token":")[^"]*'

As result I get:

022-8baa5324-f57b-445d-c5ec-821c63a5fd35

My problem is that MacOS does not support the grep parameter P (Perl expression) anymore. Parameter E does not work with that expression.

I would appreciate any help with a solution without requiring to install additional Bash tools.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
J. Doe
  • 31
  • 1
  • 2

1 Answers1

2

Everyone says they don't want to install new tools, but really, line-oriented tools like grep simply weren't designed to cope with structured text like JSON. If you are going to work with JSON, get tools designed to process it.

jq is one such option:

$ echo "$response_json" | jq -r '.access_token'
022-8baa5324-f57b-445d-c5ec-821c63a5fd35
chepner
  • 497,756
  • 71
  • 530
  • 681