Url manipulation | Extract filename from URL in bash script

Written on 05 February 2017

Task:
Extract filename and path from URL in bash script

Example we have link http://blog.sudoask.com/sitemap-posts.xml
And we want just sitemap-posts.xml
We can use basename command

$ basename http://blog.sudoask.com/sitemap-posts.xml

Get result in a variable

$ url="http://blog.sudoask.com/sitemap-posts.xml"
$ file=$(basename $url)
$ echo $file

If you just want sitemap-posts just add .xml to basename command

$ basename -s .xml http://blog.sudoask.com/sitemap-posts.xml

Or you may want to get domain name

$ echo "http://blog.sudoask.com/sitemap-posts.xml"|awk -F '/'  '{print $3}')