You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优雅实现Curl批量下载链接并按URL末3段路径保存文件?

批量下载URL并按路径段保存的优雅写法

原命令依赖硬编码的路径段索引(cut -f5-),如果URL前缀结构变化就会失效,且循环内多次子shell调用效率偏低。以下是几种更鲁棒、高效的优化方案:

方案1:用jq直接生成curl命令(最简洁)

利用jq的字符串处理能力,直接构造出每个URL对应的curl下载命令,再交给shell执行。无需循环,自动适配任意前缀长度的URL,动态取最后3个路径段:

curl https://data.ninjakiwi.com/btd6/races | jq -r '
  .body[] | (.leaderboard, .metadata) | 
  "curl --create-dirs -o \"\( [split("/")[-3], split("/")[-2], split("/")[-1]] | join("/") ).json\" \"\(.)\""
' | sh

方案2:bash内置参数扩展处理(无外部依赖)

如果运行环境是bash,可利用内置的参数扩展和数组功能处理路径,减少外部命令调用,提升效率:

curl https://data.ninjakiwi.com/btd6/races | jq -r '.body[] | .leaderboard, .metadata' | while read -r url; do
  # 剥离协议和域名,保留路径部分
  path="${url#*://*/}"
  # 将路径拆分为数组
  IFS='/' read -ra path_parts <<< "$path"
  part_count=${#path_parts[@]}
  # 拼接最后3个路径段作为输出路径
  output="${path_parts[part_count-3]}/${path_parts[part_count-2]}/${path_parts[part_count-1]}.json"
  curl --create-dirs -o "$output" "$url"
done

方案3:xargs并行下载(提升速度)

如果需要批量下载提速,可结合xargs的并行参数-P,同时发起多个curl请求:

curl https://data.ninjakiwi.com/btd6/races | jq -r '
  .body[] | (.leaderboard, .metadata) | 
  [split("/")[-3], split("/")[-2], split("/")[-1]] | join("/") + ".json" as $output | 
  "\(.)|\($output)"
' | xargs -d'\n' -P4 -I{} sh -c '
  url=$(echo "{}" | cut -d"|" -f1)
  output=$(echo "{}" | cut -d"|" -f2)
  curl --create-dirs -o "$output" "$url"
'

将-P4改为你需要的并行数即可(比如-P8同时下载8个)。

内容的提问来源于stack exchange,提问作者qwr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 14:49:57