|
|
有胆有识的牛肉面 · 这么多人都把屏幕调成黑白色?网友:能省很多钱 ...· 5 月前 · |
|
|
行走的豆芽 · 2013年广东省人民检察院工作报告· 1 年前 · |
|
|
温文尔雅的皮蛋 · 北汽HOEN O2申报图曝光 ...· 2 年前 · |
|
|
豪情万千的眼镜 · 关于影帝� - 搜狗图片搜索· 2 年前 · |
|
|
好帅的小刀 · linux shadow文件破解-掘金· 2 年前 · |
我希望在Linux中使用Grep从JSON响应中提取oid值,并将其存储在变量$oid中。JSON存储在变量$Response中
我的代码
oid= $Response | grep -Po '"oid": *\K"[^"]\*"'
My JSON (简写)
{
"count": 1,
"items": [{
"oid": "xyzxyzxyzxyzxyzxyzxyz",
"creationDate": "2019-02-05T02:21:08.662+0000"
}
实际行为 :当我回送$oid时,它是空的(例如,Grep没有从JSON中提取任何值)
预期行为 :$oid保存从JSON中提取的样例(在本例中是
发布于 2022-07-26 13:29:29
由于OP清楚地提到了json解析器不能被使用,所以在GNU
grep
中不能这样回答。用GNU
grep
编写和测试,仅显示示例。而且,专家们总是建议使用json解析器,所以如果您有兴趣的话。
echo "$Response" | grep -ozP '(^|\n){\n"count":\s+[0-9]+,\n"items":\s+\[{\n\s+"oid":\s+"\K[^"]*'
输出如下:
xyzxyzxyzxyzxyzxyzxyz
regex的
解释:
添加了对上述regex使用的详细说明,它仅用于解释目的,如需使用,请参阅上面的GNU
grep
命令。
(^|\n){\n ##Matching new line OR starting here followed by { and new line.
"count":\s+ ##Matching "count": followed by 1 or more spaces.
[0-9]+,\n ##Matching 1 or more digits followed by comma followed by new line.
"items":\s+ ##Matching "items": followed by 1 or more spaces.
\[{\n\s+ ##matching literal [ followed by { new line and spaces.
"oid":\s+" ##Matching "oid": followed by 1 or more spaces followed by " here.
\K ##Here is GNU grep's GREAT option \K which helps us to forget previous match.
##Basically match everything but forget its value so that we can get only required values.
[^"]* ##Match everything just before next occurrence of " here.
发布于 2022-07-26 18:58:48
试试这个:
Response='
"count": 1,
"items": [{
"oid": "xyzxyzxyzxyzxyzxyzxyz",
"creationDate": "2019-02-05T02:21:08.662+0000"