2

I have a JSON input:

{
  "policyItems": [
    {
      "accesses": [
        {
          "type": "submit-app",
          "isAllowed": true
        }
      ],
      "users": [],
      "groups": [
        "Application_Team_1",
        "team2"
      ],
      "conditions": [],
      "delegateAdmin": false
    }
  ]
}

I did a command line curl to dispaly the queue policy yarn:

curl  -u "login:password" http://myHost:6080/service/public/v2/api/service/YARN_Cluster/policy/YARN%20NameQueue/

It works fine.

Then I added grep to extract all the list of groups items:

curl  -u "login:password" http://myHost:6080/service/public/v2/api/service/YARN_Cluster/policy/YARN%20NameQueue/ | 
grep -oP '(?<="groups": ")[^"]*'

This following is the result:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   579    0   579    0     0   4384      0 --:--:-- --:--:-- --:--:--  4419

It is not working. How can I do it using grep and not jq ?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
vero
  • 1,005
  • 6
  • 16
  • 29

1 Answers1

1

You may use

grep -Poza '(?:\G(?!^)",|"groups":\s*\[)\s*"\K[^"]+'

Options

  • P - use PCRE engine to parse the pattern
  • o - output matches found
  • z - slurp the whole file, treat the file as a whole single string
  • a - treat the file as a text file (it should be used because when the -z switch may trigger grep binary data behaviour that changes the return values).

Pattern

  • (?:\G(?!^)",|"groups":\s*\[) - either the end of the previous match (\G(?!^)) and then ", substring, or (|) a literal text "groups":, 0+ whitespaces (\s*) and a [ char (\[)
  • \s*" - 0+ whitespaces and " char
  • \K - match reset operator discarding the whole text matched so far
  • [^"]+ - 1+ chars other than "

As you see, this expression finds "group": [", omits that text and matches each value inside "s only after that text.

See the PCRE regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Can you help me on this question is related to regex https://stackoverflow.com/questions/51065117/find-string-in-substring-regex – vero Jun 27 '18 at 14:23