在MacOS上匹配正则表达式并提取json中的所有实例
所以我有一个脚本,它返回一个 json 响应,其中包含一个键 Name 和一个文件名。
所以我设法让它在 GNU grep 中工作,但现在我需要它在 macOS 上运行,无需安装任何东西,而且 FBSD grep 不能使用 Perl 语法。知道如何做到这一点吗?
变量 files 包含 json-response。
这适用于 GNU grep:
files=($(echo $files | grep -oP '"Name":"s*K[^s,]*(?=s*",)'))
返回 file01.jpg、file02.jpg 等并将其存储在数组中。
json 响应的示例在此处格式化,但在一行中:
{
"value": [
{
"Name": "file01.jpg",
"TimeCreated": "2021-05-12T12:46:10Z",
"TimeLastModified": "2021-05-12T12:46:10Z",
"Title": null
},
{
"Name": "file02.jpg",
"TimeCreated": "2021-05-12T12:46:10Z",
"TimeLastModified": "2021-05-12T12:46:10Z",
"Title": null
}
]
}
它在 files 变量中的显示方式:
{"value":[{"Name":"file01.jpg","TimeCreated":"2021-05-12T12:46:10Z","TimeLastModified":"2021-05-12T12:46:10Z","Title":null},{"Name":"file02.jpg","TimeCreated":"2021-05-12T12:46:10Z","TimeLastModified":"2021-05-12T12:46:10Z","Title":null}]}
回答
如果您有 GNU awk,请尝试以下解决方案。
awk -v RS='"Name": "[^"]*' 'RT{gsub(/.*"/,"",RT);print RT}' Input_file
解释:简单的解释是,使用 GNUawk,将 RS(记录分隔符)设置为"Name": "直到下一次出现". 然后在主程序中,如果 RT 不为空,则替换其中的所有"内容并打印它,这将是 OP 所需的值。