kingunits
kingunits

Reputation: 107

bash regexp "find anything between last slash and dot"

the source string is a path, let's say

/home/test/test/filename.ext

I need to match filename from path and catch it in a BASH_REMATCH

I've tried hundred of figures, it really makes my eyes water, the closest is

/[^/]*.$

but it only match filename.ext

and \/([a-zA-Z0-9]+)\.

but it match /filename.

Thank you

Upvotes: 2

Views: 384

Answers (2)

user557597
user557597

Reputation:

You should use the end anchor

([^/]+)\.[^/.]+$  

Then filename is in group 1.

Upvotes: 0

anubhava
anubhava

Reputation: 785886

You can use:

s='/home/test/test/filename.ext'
[[ "$s" =~ /([^./]+)\. ]] && echo "${BASH_REMATCH[1]}"
filename

Upvotes: 3

Related Questions