Given the full path to a file, how do I get just the path without the filename?

后端 未结 2 523
小蘑菇
小蘑菇 2021-01-22 01:37

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 rege

相关标签:
2条回答
  • 2021-01-22 02:02

    split on "/", remove last element and join them back.

    $path='/home/user/directory/HelloWorld.txt';
    @s = split /\// ,$path;
    pop(@s);
    print join("/",@s);
    
    0 讨论(0)
  • 2021-01-22 02:08

    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"
    
    0 讨论(0)
提交回复
热议问题