Sup*_*DOS 1 regex macos bash grep
所以我有一个脚本,它返回一个 json 响应,其中包含一个键 Name 和一个文件名。
所以我设法让它在 GNU grep 中工作,但现在我需要它在 macOS 上运行,无需安装任何东西,而且 FBSD grep 不能使用 Perl 语法。知道如何做到这一点吗?
变量 files 包含 json-response。
这适用于 GNU grep:
files=($(echo $files | grep -oP '"Name":"\s*\K[^\s,]*(?=\s*",)'))
Run Code Online (Sandbox Code Playgroud)
返回 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
}
]
}
Run Code Online (Sandbox Code Playgroud)
它在 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}]}
Run Code Online (Sandbox Code Playgroud)
像这样的工具jq总是更适合解析 JSON,但如果您无法安装它(如问题所述),那么请考虑这个grep + awk:
grep -oE '"Name":\s*"[^\s,"]*' file.json | awk -F '"' '{print $NF}'
file01.jpg
file02.jpg
Run Code Online (Sandbox Code Playgroud)
如果您有 GNU awk,请尝试以下解决方案。
awk -v RS='"Name": "[^"]*' 'RT{gsub(/.*"/,"",RT);print RT}' Input_file
Run Code Online (Sandbox Code Playgroud)
解释:简单的解释是,使用 GNUawk,将 RS(记录分隔符)设置为"Name": "直到下一次出现". 然后在主程序中,如果 RT 不为空,则替换其中的所有"内容并打印它,这将是 OP 所需的值。