Removing everthing after the second last "/"

Hi,
     I've got a path and I'd like drop down one dir by simply editing the string.  So I want to be able to change /u3/user/public_html/otherdir/ to /u3/user/public_html/ how would I do this easily?
cideAsked:
Who is Participating?
 
alamoConnect With a Mentor Commented:
The easy way is:

$path = "/u3/user/public_html/otherdir/";
$path =~ s![^/]+/$!!;
print "$path\n";

Will print:
/u3/user/public_html/

This regexp assumes that the string ends in /, and the directory separator will always be /, which your question implies.

Hope this solves your problem, good luck!
0
 
alamoCommented:
Just to explain a little more:

The regular expression "[^/]+/$" matches any character other than / (the "[^/]" part), one or more times (the "+" part"), ending in a "/" at the end of the line (the "$" part).

The "+" part will attempt to match as many characters as it can, which is how it matches the entire last directory name.
0
 
cideAuthor Commented:
Nice work, thanks a bunch! :)
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
cideAuthor Commented:
Nice work, thanks a bunch! :)
0
 
tpryorCommented:
$path = "/u3/user/public_html/otherdir/";

$path =~ /(^.*\/).+\/;
$new_path = $1;

this will work for path's with trailing slashes or not.  ex: "/u3/user/public_html/otherdir"  or
"/u3/user/public_html/otherdir/"

$new_path will allways be shorter by one dir.

GL,
t
0
 
cideAuthor Commented:
Interesting! :)
Regexp really make perl useful.
0
 
cideAuthor Commented:
Interesting! :)
Regexp really make perl useful.
0
 
alamoCommented:
Yes, very much so cide. It's amazing what a regexp can do - the only downside is they can be somewhat cryptic and tricky to debug when they don't work.

By the way tpryor, your last regexp gave "Search pattern not terminated" when I tried it.
0
 
cideAuthor Commented:
Interesting! :)
Regexp really make perl useful.
0
 
tpryorCommented:
those \ chars are actually backslashes

it will do the trick

t
0
 
tpryorCommented:
oops, somethin got copied wrong.
should be...

$path =~ /(^.*\/).+$/;
$new_path = $1;

or

$path =~ s/(^.*\/).+$/$1/;

that will do it.

regex gotta love it!
t
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.