HackerGamerLV HackerGamerLV - 9 days ago 6
Bash Question

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

In a shell script i have a variable

$FILE_LINK
, which contains the following string:

http://links.twibright.com/download/links-2.13.tar.gz


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
    $FILE_LINK

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

  3. Store the string in a variable
    $FILE_LINK_NAME




How i could achieve that?

Answer

If using BASH use:

file_link='http://links.twibright.com/download/links-2.13.tar.gz'
file_link_name="${file_link##*/}"

links-2.13.tar.gz

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.

Comments