$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.)
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.
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.
On Windows, both slash ( / ) and backslash ( \ ) are used as directory separator character. In other environments, it is the forward slash ( / ).
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.
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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With