Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

How do I change .. to the real filename?

( #53416=categorized question: print w/ replies, xml ) Need Help??
Contributed by dcardamo on Jan 22, 2001 at 08:09 UTC
Q&A  > regular expressions


Description:

I have a filename with the entire path '/home/projects/..' The '..' means to go back a directory, so its real path is '/home' Can this be done with a regex or do I have to split this?

Answer: How do I change .. to the real filename?
contributed by merlyn

use File::Spec; print File::Spec->rel2abs("/home/projects/..");
Answer: How do I change .. to the real filename?
contributed by AltBlue

use Cwd 'abs_path'; print abs_path('/home/projects/..');
Answer: How do I change .. to the real filename?
contributed by matthewm

To answer your specifc example..

$file =~ s%/[^/]+/\.\.$%%
... will eat the last directory name that's up'ed by the trailing ..
To give a more general/complete example that can handle multiple .'s and ..'s at any point in the path.
# colapse /./ and /.$ 1 while ($file =~ s%/\.(/|$)%$1%g); # colapse /dir/../ and /dir/..$ # ignore /../../ and /../..$ 1 while ($file =~ s%/[^/]+/(?<!/\.\./)\.\.(/|$)%$1%g); # remove ^dir/../ and ^dir/../ # ignore ^../../ and ^../.. 1 while ($file =~ s%^[^/]+/(?<!^\.\./)\.\.(/|$)%%); # colapse ^/../ to / 1 while ($file =~ s%^/\.\./%/%); # expand null to . $file =~ s%^$%.%;
We need the itterations of each loop as each substitution may reveal additional matchs.
We need multiple expressions to get the order of susbistion right. That is /../../ should colapse the two proceding directoires and not itself.
I'm sure it can be reduced more than that but it is as simple as I can see it can be and still catch all the special cases.
I use something very similar to this at the beginning of my scripts to get the conical path for $0 and not the called path. Although spliting the path into its components and working backwards is probably easier/clearer than using a regex.
Answer: How do I change .. to the real filename?
contributed by dcardamo

I tried the first solution, and it didn't work properly. I haven't tried the second, but here is a non-regex routine that I wrote to do that:

sub relpath($) { my $file = shift; my $newfile = ""; $file =~ s/\n//g; # remove new lines my @peices = split /\//, $file; for (my $i = 0; $i <= $#peices; $i++) { if ($peices[$i + 1] eq "..") { last; } if ($peices[$i] ne ".") { $newfile .= "/$peices[$i]"; } } $newfile =~ s/\/\//\//g; return $newfile; }
Answer: How do I change .. to the real filename?
contributed by Shakya

You can even try this -

1 while ($string =~ s!(/(?:[^/.]+/)*)((?:[^/.]+/)+\.\./?)(.*)$!$1$3!g) +;

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others imbibing at the Monastery: (10)
    As of 2015-07-29 12:03 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









      Results (263 votes), past polls