regex to select last part of a path

Hi all,
I am learning the use of regular expression and I would like to know which regex can be used to select only the last part of a directory path name.

Something like:
/dir1/dir2/dir2
and I want to select the last /dir2 where dir2 can be any kind of string.

Thanks a lot for your help. Cheers,
Elric

This isn't regex (at least I don't think it is) but you could accomplish it like this:

$ cat test.sh
#!/bin/bash
string="/dir1/dir2/dir2"
echo $string
string=${string##*/}
echo $string

$ ./test.sh
/dir1/dir2/dir2
dir2

Actually, after I posted this I reread your "I am learning the use of regular expression" line. My post isn't relevant

In Perl it would be

$string = "/dir1/dir2/dir2";
$string =~ m|(/.+?)$|;
print $1;

thanks to everybody but I think there is a problem because the output printed by the perl script is:

/dir1/dir2/dir2

I think it is due to the ".+" that includes the / character so it matches all the string starting from the first /dir1. Or maybe I did something wrong in my script... I am checking.
However, how can I veto the / from .+ ?

Hm, you're right, should have checked that. Change that from (/.+?) to (/[^/]+?) and it should be fine.

You're right; the shell uses filename expansion patterns, not regular expressions.

I works perfectly, thanks to everyone ! :slight_smile:

you can use a regex like :

sed 's:.*/:/:g' <<< "/dir1/dir2/dir2"