Using sed and regex to grab the last part of a url

I am trying to get sed to match the last part of the url and output exactly that. For instance:

echo "http://randomurl/suburl/file.mp3" | sed (expression)

should produce the result:

file.mp3

So far I have tried sed 's|\([^/]+mp3\)$|\1|g', but it just displays the whole URL. Maybe there is something I don’t see here, but in any case, help would be greatly appreciated!

+5
source share
4 answers

it works:

 echo "http://randomurl/suburl/file.mp3" | sed 's#.*/##'
+11
source

basename - your good friend.

> basename "http://randomurl/suburl/file.mp3"
=> file.mp3
+6
source

:

$ echo "http://randomurl/suburl/file.mp3" | sed -r 's|.*/(.*)$|\1|'
file.mp3

:

  • | / s.
  • , /.

: bash :

$ url="http://randomurl/suburl/file.mp3"
$ echo ${url##*/}
file.mp3
+3
echo 'http://randomurl/suburl/file.mp3' | grep -oP '[^/\n]+$'

, grep.

+2

All Articles