JSON 文件中以不同字符串开头、包含和结尾的下载 URL

Download URLs in JSON file starting with, including, and ending with different strings

我有一个终端命令,我 运行 下载提供的 JSON 文件中包含的所有 URL:

egrep -o 'https:[^\"]*png' file-name.json | xargs -n 1 curl -O

这按预期工作,但一些 URL 位于不同的 "sub-folders",例如:

https://website.com/a-folder-name/display/image.png

https://website.com/another-folder-name/display-side/image.png

https://website.com/a-different-folder-name/thumb/image.png

我想调整此命令以仅从指定文件夹名称检索文件(这样我可以再次 运行 命令,更改子文件夹名称以仅检索每个文件夹中的图像),例如:

下面是我的 JSON 数据的示例:

{
  "parent_groups": [
    {
      "id": 1,
      "name": "Main name",
      "groups": [
        {
          "id": 3,
          "name": "Sub Name",
          "components": [
            {
              "id": "id-number",
              "name": "Unit name",
              "image": "https://website.com/a-folder-name/display/image.png"
            },
            {
              "id": "another-id-number",
              "name": "Another Unit name",
              "image": "https://website.com/another-folder-name/display/another-image.png"
            }
          ]
        }
      ]
    }
  ],
  "display": {
    "side": {
      "components": [
        {
          "id": "side-id",
          "filename": "https://website.com/another-folder-name/display-side/image.png"
        },
        {
          "id": "another-side-id",
          "filename": "https://website.com/some-folder-name/display-side/another-image.png"
        }
      ]
    },
    "main": [
      {
        "position": 0,
        "conditions": [
          {
            "ids": [
              "thumb-id9"
            ],
            "filename": "https://website.com/irrelevant-folder-name/thumb/image.png"
          },
          {
            "ids": [
              "another-thumb-id"
            ],
            "filename": "https://website.com/this-is-a-folder-name/thumb/another-image.png"
          }
        ]
      }
    ]
  }
}

这是我使用的文件的大量缩减,但希望能作为一个相关示例。

是这样的吗?

egrep -o 'https:[^"]*/display-sides/[^"]*png' file-name.json | xargs -n 1 curl -O

如果将周围的引号也考虑在内,这可能会变得更加稳健:

egrep -o '"https:[^"]*/display-sides/[^"]*png"' file-name.json | tr -d '"' | xargs -n 1 curl -O

如果您愿意,这将允许您也放弃 png 文件扩展名。

grep 不是处理 JSON 数据的正确工具。

使用jq工具的正确方法:

jq '.. | select(type =="string" and 
                test("^https://.+display-side.+\.png$"))' file-name.json | xargs -n1 curl -O

这将独立于键名查找所有 url。
它还可以扩展为仅分析特定键。

@Roman 是对的,如果您真正 寻找的是 JSON-structure:

中的字段
jq -r '.display.side.components[].filename' foo.json |
  parallel curl -O