wget URL多重大括号展开:批量下载不同位数命名的图片
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
%doutputs the number as-is (e.g., 1 →1)%02dpads to 2 digits with leading zeros (e.g., 1 →01)%03dpads to 3 digits with leading zeros (e.g., 1 →001)- Using
|| trueinstead ofbreakensures 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 -wenables "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

