Bash Shell – Extract Base File Name from URL

shellstring

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

I expected this code to print file.ext, but it prints the whole URL. Why? How can I extract the file name?

Best Answer

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
Related Question