-1

Inside my bash script I've created a function that returns the following JSON array:

{
    "access_token": "sjdhjdYdjsdbhggjhSJ78dbdsdbMhd=",
    "scopes": "repository:delete repository:admin repository:write project:write team:write account:write",
    "expires_in": 3600,
    "refresh_token": "skdjKJDJDBNBDs",
    "token_type": "bearer"
} 

Now I wan't to grep the access token between the "". So I got sjdhjdYdjsdbhggjhSJ78dbdsdbMhd=

I've created a regex like below but this returns a grep: invalid repetition count(s) error.

grep -P '\{\s*"access_token"\s*:\s*(.+?)\s*\"' foobar.txt
CodeWhisperer
  • 1,143
  • 2
  • 19
  • 39
  • One of the fun things about using unstandardized functionality is that their behavior differs across systems based on variables such as which libpcre your grep was compiled against. On my system (GNU grep 3.1, libpcre 8.41), your original code works unmodified. – Charles Duffy Aug 15 '17 at 15:09
  • @Gavin, if you were able to repro the OP's bug, could you provide version info? – Charles Duffy Aug 15 '17 at 15:10
  • (BTW, I'm assuming that the real data doesn't have newlines -- despite such newlines being given in the question -- as the given `grep` command isn't running in multiline mode, and won't match a newline under `\s`). – Charles Duffy Aug 15 '17 at 15:11
  • Closely related: [Parsing JSON with UNIX tools](https://stackoverflow.com/questions/1955505/parsing-json-with-unix-tools) – Charles Duffy Aug 15 '17 at 15:12
  • Actually, [Extract JSON value in bash](https://stackoverflow.com/questions/39022949/extract-json-value-in-bash) appears to be trying to parse the exact same kind of token you are, and has held up to a close vote as a duplicate of the above, so... there we are. – Charles Duffy Aug 15 '17 at 15:13

1 Answers1

1

Since you're dependending on nonstandard, nonportable functionality (in the form of grep -P), you might as well switch to a tool that's built for the job at hand (and actually understands JSON syntax, so it'll work even if your input has, say, a newline between the key and value, so long as it's syntactically valid):

jq -r .access_token <foobar.txt
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441