LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Perl, Removing file from path to get directory only (https://www.linuxquestions.org/questions/programming-9/perl-removing-file-from-path-to-get-directory-only-447322/)

xemous 05-22-2006 06:38 AM

Perl, Removing file from path to get directory only
 
I need to remove the file name from a path, eg:

$fpath = /home/user/hello/hey.pl

So I can make it...

$fpath2 = /home/user/hello

Instead.

Is there an easy way to do this, like some inbuilt function?

druuna 05-22-2006 07:14 AM

Hi,

Take a look at: File::Basename

It can do a lot more then you ask, with that in mind here's a code snippet:

Code:

#!/usr/bin/perl

use strict;
use warnings;

use File::Basename;

my $fpath = "/home/user/hello/hey.pl";

print "Original  : " . $fpath . "\n";

my($filename, $directories) = fileparse($fpath);

print "Filename  : " . $filename    . "\n";
print "Directory : " . $directories . "\n";

Hope this helps.

xemous 05-22-2006 01:44 PM

I love you.

introuble 05-23-2006 12:32 AM

*Or* (I don't see much reason to do this but..) you can use the dirname(1) utility.

druuna 05-23-2006 09:25 AM

Hi,

True, you could use dirname (1), but it's an external (unix) command, seen from perl that is.

dirname [File::Basename] (3) is also part of File::Basename and an internal perl command, which is more resource friendly.

Hope this clears things up a bit.

vammydhar 09-02-2008 01:53 PM

thanks
 
Thanks for the above soultion

druuna 09-02-2008 02:12 PM

:-)

You are welcome!

isisira 04-11-2012 12:25 AM

Thank you
 
Hi! Thank you.. A colleague today asked me how to do this and I directly got the answer when i came here..perfectly worked!

theNbomr 04-11-2012 11:13 AM

The Perl code to do this can be as simple as (if $filename contains fully qualified filespec):
Code:

$filename=~m/^.+\//;
$path=$&;

Relies on greedy matching that is default in Perl.

--- rod.


All times are GMT -5. The time now is 04:09 PM.