0

So I have a list of downloadable links with a specific order, but the filenames are jumbled up

example.com/ddk.zip
example.com/453.zip
example.com/hth.zip

So I want to automatically prefix them as I download them, based on the order of the list of links, so they'd look like this:

001_ddk.zip
002_453.zip
003_hth.zip

Is there any way to achieve this in Bash?

  • What are you stuck on? wget downloads a file. Remember to prefix the link with http:// or https://. Once downloaded you can rename the file with mv. – Philip Couling May 20 at 6:33
1

Here is a piece of script

#!/bin/bash

PATH=/bin:/sbin:/usr/bin:/usr/sbin

prefix=1

while read link; do
  filename="$(printf "%03d" $prefix)_${link##*/}"
  echo "wget $link -O $filename"
  prefix=$((prefix+1))
done < <(cat /tmp/list)

obviously remove the the echo on the wget command to execute it for real

result:

$ bash script.sh
wget example.com/ddk.zip -O 001_ddk.zip
wget example.com/453.zip -O 002_453.zip
wget example.com/hth.zip -O 003_hth.zip
wget example.com/ddhth.zip -O 004_ddhth.zip
wget example.com/hggth.zip -O 005_hggth.zip
wget example.com/jhkhth.zip -O 006_jhkhth.zip

And yep, you'll need to edit your link list and add http:// or https:// before

  • What if your links are already in "http://example.com/file.zip" format? With an arbitrary number of slashes, how would you trim it down to just the filename? – doko May 20 at 10:12
  • my bad, I edited my script to keep only the text after the last slash (## instead of #) – darxmurf May 20 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.