Reputation: 10362
$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.)
Upvotes: 15
Views: 20686
Reputation: 11
try this; it works at least for the filename, but when you modify it, it also gives you the direction: You can also modify it on UNIX-systems for the \ instead if / or to use them both with |
$filename =~ s/(^.*\/)//g;
Upvotes: 1
Reputation: 882346
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
Upvotes: 25
Reputation: 471
Use @array = split("/", $a);
and then $array[-1]
is your file name.
Upvotes: 1
Reputation: 133
I think a regex solution is a perfectly legitimate need - since my googling for exactly that brought me here. I want to pull out a filename in a group that's part of a larger match expression - here's my attempt:
~> echo "/a/b/c/d" | perl -ne '/(?<dir>\/(\w+\/)*)(?<file>\w+)/ && print "dir $+{dir} file $+{file}\n";'
dir /a/b/c/ file d
Upvotes: 1
Reputation: 46985
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/
Upvotes: 16
Reputation: 76006
For example:
$a =~ m#^(.*?)([^/]*)$#;
($dir,$file) = ($1,$2);
But, as other said, it's better to just use Basename
for this.
And, BTW, better avoid $a
and $b
as variable names, as they have a special meaning, for sort
function.
Upvotes: 0