HackerGamerLV HackerGamerLV - 10 months ago 51
Bash Question

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

In a shell script i have a variable

, which contains the following string:


What i need is to get the filename from the link, and store it in a different variable, so the process would look similar to this:

  1. Set variable

  2. Get the last string after the last "/", in this case 'links-2.13.tar.gz'

  3. Store the string in a variable

How i could achieve that?

Answer Source

If using BASH use:



Or else use basename (not available on OSX):

file_link_name=$(basename "$file_link")

If not use this awk:

file_link_name=$(awk -F / '{print $NF}' <<< "$file_link")

Or using sed:

file_link_name=$(sed 's~.*/~~' <<< "$file_link")

PS: I'm avoiding all uppercase variable names in order to avoid clash with ENV variables.