How to Specify a Custom Output Filename in Wget?
When downloading files using the wget command-line
utility, the tool automatically names the saved file based on the last
portion of the URL. However, you can easily override this default
behavior and specify a custom output filename by using the
-O (uppercase letter O) option. This article provides a
quick overview of how to rename files during a download, handle
different directory paths, and avoid common syntax pitfalls.
The Basic Syntax for Renaming Downloads
To save a downloaded file under a specific name, append the
-O option followed by your desired filename. The basic
structure of the command looks like this:
wget -O custom_name.ext "URL"
For example, if you want to download a text file but save it as
my_notes.txt, you would run the following command in your
terminal:
wget -O my_notes.txt "https://example.com/downloads/file-xyz.txt"
Saving to Specific Directories
The -O option is not limited to just changing the
filename; it also accepts absolute or relative directory paths. This
allows you to download and move a file to a specific folder in a single
step.
- Relative Path:
wget -O documents/report.pdf "https://example.com/report" - Absolute Path:
wget -O /home/user/downloads/image.png "https://example.com/img"
If the directories specified in the path do not exist,
wget will fail to create the file, so ensure the target
folder is already created before running the command.
Key Gotchas and Best Practices
While using the -O flag is straightforward, there are a
few important technical behaviors to keep in mind to prevent accidental
data loss:
- Case Sensitivity: Always use an uppercase
-O. Using a lowercase-oredirects thewgetlog output to a text file rather than changing the downloaded file’s name. - Overwriting Existing Files: If a file with your
custom name already exists in the destination folder,
wgetwill overwrite it without warning. - Handling Multiple URLs: If you pass multiple URLs
to a single
wgetcommand while using the-Ooption,wgetwill concatenate all the downloaded contents into that single file. For downloading multiple files with unique names, it is best to run separate commands or use a script loop.