How to get the filename from a http link in linux?

by viola_gleichner , in category: General Help , a month ago

How to get the filename from a http link in linux?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer


by adelia , a month ago


In Linux, you can use the basename command along with the curl command to extract the filename from an HTTP link. Here's how you can do it:

  1. Install the curl package (if not already installed) by running the following command: sudo apt-get install curl
  2. Once installed, you can use the curl command with the -I option to retrieve the HTTP headers from the link and search for the Content-Disposition header, which often includes the filename. curl -I The output will contain the HTTP headers. Look for the Content-Disposition header. If present, it may look like this: Content-Disposition: attachment; filename="file.pdf"
  3. Finally, use the basename command to extract the filename from the header. basename $(curl -s -I | grep -i content-disposition | awk -F" '{print $2}') This command uses command substitution ($(command)) to capture the output of curl, grep, and awk commands and then extracts the filename using basename. You need to replace with your desired HTTP link.

Note: This method assumes that the HTTP server provides the filename in the Content-Disposition header. However, not all servers return this header, so it might not always work.