How to get last part of http link in Bash?
Using awk
for this would work, but it's kind of deer hunting with a howitzer. If you already have your URL bare, it's pretty simple to do what you want if you put it into a shell variable and use bash
's built-in parameter substitution:
$ myurl='http://www.example.com/long/path/to/example/file.ext'
$ echo ${myurl##*/}
file.ext
The way this works is by removing a prefix that greedily matches '*/', which is what the ##
operator does:
${haystack##needle} # removes any matching 'needle' from the
# beginning of the variable 'haystack'
basename
and dirname
work good for URLs too:
> url="http://www.test.com/abc/def/efg/file.jar"
> basename "$url"; basename -s .jar "$url"; dirname "$url"
file.jar
file
http://www.test.com/abc/def/efg
With awk
, you can use $NF
, to get the last field, regardless of number of fields:
awk -F / '{print $NF}'
If you store that string in shell variable, you can use:
a=http://www.test.com/abc/def/efg/file.jar
printf '%s\n' "${a##*/}"