Reputation: 39
I want to split out a directory based on a given directory path with comparison to a default directory in perl preferably in regex. I have two default directories, lets say /root/demo/ and /etc/demo/.
Given a directory path, lets say /root/demo/home/test/sample/somefile.txt OR /etc/demo/home/test/sample/somefile.txt,
I want to extract the /home/test/sample/somefile.txt from the given directory path. Kindly assist.
Thanks
Upvotes: 0
Views: 50
Reputation:
Here is another way using quotemeta.
Perl sample:
use strict;
use warnings;
my @defaults = ('/root/demo/', '/etc/demo/');
$/ = undef;
my $testdata = <DATA>;
my $regex = '(?:' . join( '|', map(quotemeta($_), @defaults) ) . ')(\S*)';
print $regex, "\n\n";
while ( $testdata =~ /$regex/g )
{
print "Found /$1\n";
}
__DATA__
/root/demo/home/test/sample/somefile.txt
/etc/demo/home/test/sample/somefile.txt
Output:
(?:\/root\/demo\/|\/etc\/demo\/)(\S*)
Found /home/test/sample/somefile.txt
Found /home/test/sample/somefile.txt
Upvotes: 1
Reputation: 35198
Build your list of prefix dirs into a regex alteration. Be sure to sort by length
descending, and also to use quotemeta
.
The following demonstrates:
use strict;
use warnings;
my @dirs = qw(
/root/demo
/etc/demo
);
# Sorted by length descending in case there are subdirs.
my $list_dirs = join '|', map {quotemeta} sort { length($b) <=> length($a) } @dirs;
while (<DATA>) {
chomp;
if ( my ($subdir) = m{^(?:$list_dirs)(/.*)} ) {
print "$subdir\n";
}
}
__DATA__
/root/demo/home/test/sample/someroot.txt
/etc/demo/home/test/sample/someetc.txt
Outputs:
/home/test/sample/someroot.txt
/home/test/sample/someetc.txt
Upvotes: 1
Reputation: 174706
Use \K
to discard the previously matched characters.
\/(?:root|etc)\/demo\K\S+
Upvotes: 2