Extract the base file name from a URL using bash

Because word has to match the string to be trimmed. It should look like:

$ url="http://www.foo.bar/file.ext"; echo "${url##*/}"
file.ext

Thanks derobert, you steered me in the right direction. Further, as @frank-zdarsky mentioned, basename is in the GNU coreutils and should be available on most platforms as well.

$ basename "http://www.foo.bar/file.ext"
file.ext

To quote the manpage:

${parameter##word}
   Remove matching prefix pattern.  The word is expanded to produce
   a pattern just as in pathname expansion.  If the pattern matches
   the  beginning of the value of parameter, […]

/* does not match the beginning, because your URL starts with h not /.

A trivial way to do what you're looking for (according to your comment) is echo "$url" | rev | cut -d / -f 1 | rev. But of course, that'll give interesting results for URLs ending in a slash.

Another way to do what you want might be to use the pattern */ instead.


basename(1) works with URLs, too, so you could simply do:

url=http://www.foo.bar/file.ext; basename $url

Tags:

String

Shell