2014-11-02 2 views
0

주어진 디렉토리 경로를 기반으로 디렉토리를 분할하는 것이 좋습니다. 기본 디렉토리 인 perl을 선호하는 것이 좋습니다. 두 개의 기본 디렉토리가 있는데/root/demo /와/etc/demo /라고 말하면됩니다. 디렉토리 경로 감안할 때 기본 디렉토리를 기반으로 디렉토리를 결정하십시오.

는 는 /root/demo/home/test/sample/somefile.txt 또는 /etc/demo/home/test/sample/somefile.txt, 내가 원하는

을 말할 수 주어진 디렉토리 경로에서 /home/test/sample/somefile.txt를 추출합니다. 친절하게 도와주세요.

감사

답변

2

Use \K 이전에 일치하는 문자를 삭제합니다.

\/(?:root|etc)\/demo\K\S+ 

DEMO

+0

또는'\/(? 루트 | 등) \/데모 \의 K * \ \ + w (= \의 | $)' –

+0

고마워,하지만 일반 정규식을 갖고 싶다.이 정규식은/root/demo/또는/etc/demo /를 확인한다. 내 기본 디렉토리는/etc/demo/a/b/또는/root/demo/a/b /와 같이 n 레벨 디렉토리가 될 수 있습니다. 기본 디렉토리를 전달하는 Bascially는 n 레벨의 디렉토리로 구성 가능합니다. – Bablu

+0

예상 출력과 함께 더 많은 예제를 게시 할 수 있습니까? –

1

는 정규식 alteration에 접두사 DIRS의 목록을 작성합니다. length을 내림차순으로 정렬하고 quotemeta을 사용해야합니다. 여기

/home/test/sample/someroot.txt 
/home/test/sample/someetc.txt 
1

을 quotemeta를 사용하는 또 다른 방법이다 :

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 

출력을 :

다음은 보여줍니다.

펄 샘플 :

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 

출력 :.?.?

(?:\/root\/demo\/|\/etc\/demo\/)(\S*) 

Found /home/test/sample/somefile.txt 
Found /home/test/sample/somefile.txt 
관련 문제