Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I separate a full path into directory and filename?

Tags:

perl

$a = '/etc/init/tree/errrocodr/a.txt'

I want to extract /etc/init/tree/errrocodr/ to $dir and a.txt to $file. How can I do that?

(Editor's note: the original question presumed that you needed a regular expression for that.)

like image 660
Tree Avatar asked Aug 18 '10 13:08

Tree


People also ask

Does full path include filename?

Paths include the root, the filename, or both. That is, paths can be formed by adding either the root, filename, or both, to a directory.

How do you split paths?

The Split-Path cmdlet returns only the specified part of a path, such as the parent folder, a subfolder, or a file name. It can also get items that are referenced by the split path and tell whether the path is relative or absolute. You can use this cmdlet to get or submit only a selected part of a path.

Which function is used to separate a file name from its directory path?

On Windows, both slash ( / ) and backslash ( \ ) are used as directory separator character. In other environments, it is the forward slash ( / ).

How do I split a folder in path?

split() method in Python is used to Split the path name into a pair head and tail. Here, tail is the last path name component and head is everything leading up to that. In the above example 'file.


2 Answers

Just use Basename:

use File::Basename;
$fullspec = "/etc/init/tree/errrocodr/a.txt";

my($file, $dir, $ext) = fileparse($fullspec);
print "Directory: " . $dir . "\n";
print "File:      " . $file . "\n";
print "Suffix:    " . $ext . "\n\n";

my($file, $dir, $ext) = fileparse($fullspec, qr/\.[^.]*/);
print "Directory: " . $dir . "\n";
print "File:      " . $file . "\n";
print "Suffix:    " . $ext . "\n";

You can see this returning the results you requested but it's also capable of capturing the extensions as well (in the latter section above):

Directory: /etc/init/tree/errrocodr/
File:      a.txt
Suffix:

Directory: /etc/init/tree/errrocodr/
File:      a
Suffix:    .txt
like image 84
paxdiablo Avatar answered Sep 18 '22 15:09

paxdiablo


you don't need a regex for this, you can use dirname():

use File::Basename;
my $dir = dirname($a)

however this regex will work:

my $dir = $a
$dir =~ s/(.*)\/.*$/$1/
like image 24
ennuikiller Avatar answered Sep 18 '22 15:09

ennuikiller