-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
5
  • 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. Commented Aug 15, 2017 at 15:09
  • @Gavin, if you were able to repro the OP's bug, could you provide version info? Commented Aug 15, 2017 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). Commented Aug 15, 2017 at 15:11
  • Closely related: Parsing JSON with UNIX tools Commented Aug 15, 2017 at 15:12
  • Actually, 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. Commented Aug 15, 2017 at 15:13

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.