使用grep从JSON中提取字符串
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用grep从JSON中提取字符串相关的知识,希望对你有一定的参考价值。
我有一个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
呢?
答案
你可以用
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": ["
。
以上是关于使用grep从JSON中提取字符串的主要内容,如果未能解决你的问题,请参考以下文章