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

wget URL多重大括号展开:批量下载不同位数命名的图片

Handling Variable Zero-Padded Filenames for Batch Image Downloads

Great question! That nested brace expansion trick you tried ($my_url/{1..100}{01..100}{001..100}'.png') won’t work like you expect—bash brace expansion combines all elements of each range, so you’d end up with gibberish filenames like 101001.png instead of the single-number, zero-padded variations you need.

Here are a few clean, reliable ways to generate all valid filename formats (1-digit, 2-digit, 3-digit) for your download loop:

Method 1: Use printf to Generate Padding Variations

This is the most flexible approach, as it lets you explicitly define each padding format you want to check:

# Loop through each number from 1 to 100
for num in {1..100}; do
  # Check three formats: no padding, 2-digit padding, 3-digit padding
  for fmt in "%d" "%02d" "%03d"; do
    # Build the full URL
    file_num=$(printf "$fmt" "$num")
    url="$my_url/$file_num.png"
    
    # Try to download—use || true to keep going if a file doesn't exist
    wget "$url" || true
  done
done
  • %d outputs the number as-is (e.g., 1 → 1)
  • %02d pads to 2 digits with leading zeros (e.g., 1 → 01)
  • %03d pads to 3 digits with leading zeros (e.g., 1 → 001)
  • Using || true instead of break ensures the loop doesn’t stop when it hits a missing file (which is inevitable since not all formats will exist for every number).

Method 2: Use seq to Pre-Generate All Valid Numbers

If you prefer a more concise loop, you can use seq to generate all padded variations in one go:

# Combine 1-digit, 2-digit padded, and 3-digit padded numbers
all_nums=$(seq 1 100; seq -w 1 100; seq -w 001 100)

for num in $all_nums; do
  url="$my_url/$num.png"
  wget "$url" || true
done
  • seq -w enables "equal width" output, automatically adding leading zeros to match the widest number in the range.

Pro Tip: Optimize with Pre-Checks

To avoid wasting bandwidth on non-existent files, add a check with wget --spider to verify the file exists before downloading:

for num in {1..100}; do
  for fmt in "%d" "%02d" "%03d"; do
    file_num=$(printf "$fmt" "$num")
    url="$my_url/$file_num.png"
    
    # Only download if the file exists
    if wget --spider "$url" 2>/dev/null; then
      wget "$url"
      echo "Successfully downloaded $file_num.png"
    fi
  done
done

The 2>/dev/null suppresses the error messages from the spider check.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:32:37