Hello, Suppose I have a path in a string called '/home/user/directory/HelloWorld.txt'. I would like to remove the HelloWorld.txt, and end up with '/home/user/directory'. What regex would I need.
views:
89answers:
3This might work, if you're on a *nix environment. Other OSes this will fail. If this is for anything other than homework, do not use a regex. See [John Feminella's answer](http://stackoverflow.com/questions/2582132/given-the-full-path-to-a-file-how-do-i-get-just-the-path-without-the-filename/2582147#2582147) instead.
Robert P
2010-04-06 23:55:26
+15
A:
Don't use a regex. Instead, use File::Basename
, which can handle all the special cases.
use File::Basename;
dirname("/foo/bar/baz/quux.txt"); --> "/foo/bar/baz"
John Feminella
2010-04-06 01:32:56
And File::Basename will handle Windows file names where the average regex won't.
Jonathan Leffler
2010-04-06 01:52:22
From the documentation you linked to:"`dirname` This function is provided for compatibility with the Unix shell command dirname(1) and has inherited some of its quirks. In spite of its name it does NOT always return the directory name as you might expect. To be safe, if you want the directory name of a path use fileparse()."
Kinopiko
2010-04-06 04:12:15
@Kinopiko: It'll work for all reasonable cases. But yes, fileparse is just as good.
John Feminella
2010-04-06 12:05:36
Except that the author of the question needs another function, basename(), not dirname(). Basename() will return the file name (rather than the path to parent).
kirillka
2010-04-06 15:21:36
@kirillka : Unless I'm misunderstanding something, he wants just the path. "I would like to remove the HelloWorld.txt, and end up with '/home/user/directory'."
John Feminella
2010-04-06 16:48:30
And `dirname` will handle VMS where the filename format is DISK$SOMETHING:[DIR.DIR]FILE.EXT
justintime
2010-04-06 17:32:32
+1
A:
split on "/", remove last element and join them back.
$path='/home/user/directory/HelloWorld.txt';
@s = split /\// ,$path;
pop(@s);
print join("/",@s);
ghostdog74
2010-04-06 01:35:41