pp has asked for the wisdom of the Perl Monks concerning the following question:

I have the following 2 paths:
Case 1: /home/user/phase/dir1/log/Illinois/
Case 2:/home/user/phase/dir02/log/
In both the cases above I want to strip/chop off everything starting from log/ directory to the end and would want to end up with either:
Case 1:/home/user/phase/dir1/
or
Case 2:/home/user/phase/dir02/ How can I achieve this? Thanks.

Replies are listed 'Best First'.
Re: Manipulating directory paths
by moritz (Cardinal) on Sep 07, 2007 at 16:39 UTC
    If the part you want to strip off always starts with log/, that problem is not hard to solve:

    $path =~ s{log/.*$}{};

      The $ anchor is superfluous because .* is greedy and will always match to the end of the line.
        True. I know others who do this exact same thing with the dollar sign, but I think it is good for clarity when reading at a glance.
Re: Manipulating directory paths
by kyle (Abbot) on Sep 07, 2007 at 16:47 UTC

    Try this...

    $path =~ s{ /log/ .* \z }{/}xms;

    Note that if your path has "/log/" in it twice or more, this will strip off everything after the first one. If you want to strip off everything after the last one, this seems to work:

    $path =~ s{ (.*) /log/ .* \z }{$1/}xms;
      But what if I want to replace the log/ directory and after with another directory named xyz/ like:
      CASE 1:
      Before :/home/user/phase/dir1/log/
      After: /home/user/phase/dir1/xyz/
      CASE 2:
      Before: /home/user/phase/dir1/log/Illinois/
      After:/home/user/phase/dir1/xyz/
        You can either add xyz/ to the replace part of the s/// operator, or use the concatenation operator (.).
Re: Manipulating directory paths
by f00li5h (Chaplain) on Sep 08, 2007 at 06:18 UTC

    Depending where the paths came from and how likely you are to be running on interesting platforms, may want to have a look at File::Spec.

    @_=qw; ask f00li5h to appear and remain for a moment of pretend better than a lifetime;;s;;@_[map hex,split'',B204316D8C2A4516DE];;y/05/os/&print;

Re: Manipulating directory paths
by WiseGuru (Initiate) on Sep 08, 2007 at 08:42 UTC
    if you have ONLY ONE "log" directory,

    my $path = "/home/user/phase/dir1/log/Illinois/";
    my $path2;
    ($path,$path)=split(/log/,$path);

    if you have 1 or more log directories inside a log directory, then

    my $path = "/home/user/phase/dir1/log/Illinois/log/somefile/log/someotherfile...";
    my @Paths;
    @Paths=split(/log/,$path);

    then you can join any sections of the paths back together as you wish, i.e.

    $path = $Paths[0]."log".$Paths[1]."log"........

    www.arobcorp.com