使用grep从JSON中提取字符串

问题描述 投票:2回答:1

我有一个JSON输入:

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

我做了一个命令行curl来显示队列策略yarn:

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

它工作正常。

然后我添加了grep来提取所有组列表项:

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

以下是结果:

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

它不起作用。我怎么能用grep而不是jq呢?

regex shell grep rjson
1个回答
1
投票

你可以用

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

选项

  • P - 使用PCRE引擎来解析模式
  • o - 找到输出匹配
  • z - 啜饮整个文件,将文件视为一个完整的单个字符串
  • a - 将文件视为文本文件(它是should be used,因为当-z开关可能触发更改返回值的grep二进制数据行为时)。

图案

  • (?:\G(?!^)",|"groups":\s*\[) - end of the previous match\G(?!^))和",子串,或(|)文字文本"groups":,0 + whitespaces(\s*)和[ char(\[
  • qazxsw poi - 0+白色空间和qazxsw poi图表
  • \s*" - "丢弃迄今为止匹配的全文
  • \K - 除了match reset operator之外的1个字符

如您所见,此表达式查找[^"]+,省略该文本并仅在该文本之后匹配"s中的每个值。

"group": ["

© www.soinside.com 2019 - 2024. All rights reserved.