Controlling Downloaded Filenames with Wget

Controlling Downloaded Filenames with Wget

wget is a powerful command-line utility for downloading files from the internet. By default, wget saves the downloaded file using the filename present in the URL. However, you often need to rename the downloaded file to something different. This tutorial will demonstrate how to control the filename of downloaded files using wget.

The -O Option

The primary way to specify the output filename with wget is by using the -O (uppercase ‘O’) option. This option tells wget to save the downloaded content to the specified file, regardless of the filename in the URL.

The basic syntax is:

wget -O <output_filename> <url>

For example, to download https://www.example.com/textfile.txt and save it as newfile.txt, you would use:

wget -O newfile.txt https://www.example.com/textfile.txt

Important Considerations: Order of Arguments

The order of arguments is crucial when using the -O option. wget expects the -O option before the URL. The following command will not work:

wget https://www.example.com/textfile.txt -O newfile.txt

Always ensure the correct order: -O <output_filename> <url>.

Using --output-document

As an alternative, you can use the --output-document option. It achieves the same result as -O and can sometimes be more readable.

The syntax is:

wget --output-document=<output_filename> <url>

For example:

wget --output-document=newfile.txt https://www.example.com/textfile.txt

Downloading with the Remote Filename

If you want to download a file and save it with the same name as it has on the server, you can simply run wget with the URL. However, if you are downloading from a redirecting URL, it’s recommended to use curl instead, and utilize its -L or --location options to automatically follow redirects.

Example

Let’s say you want to download a zip file from a remote server and rename it locally.

wget -O my_archive.zip https://www.remotestorage.com/important_data.zip

This will download important_data.zip from the specified URL and save it as my_archive.zip on your local machine.

Using curl as an Alternative

While wget is excellent, curl is another powerful tool for downloading files. It provides similar functionality and offers more advanced options. To download a file and rename it with curl, you would use the -o option:

curl -o newfile.txt https://www.example.com/textfile.txt

Leave a Reply

Your email address will not be published. Required fields are marked *