0

I am trying to extract /temp/bin/usr/ from a variable

$path  = /temp/bin/usr/... 

using perl. Can someone help me with that ?

4
  • 1
    Have you tried anything yet? If so, please include your code. Commented Mar 5, 2013 at 15:53
  • Is that the full path or part of the file path? /temp/bin/usr/somedir/dir3/file.txt, or /temp/bin/usr/file.txt? There's a difference. Commented Mar 5, 2013 at 15:56
  • its simply /temp/bin/usr/... and i need to remove those dots Commented Mar 5, 2013 at 15:58
  • 1
    @aadi That might have been a good thing to be more specific about. Commented Mar 5, 2013 at 16:08

3 Answers 3

3

Use File::Basename. It is a core module in Perl version 5. From the documentation:

use File::Basename;

($name,$path,$suffix) = fileparse($fullname, @suffixlist);
$name = fileparse($fullname, @suffixlist);

$basename = basename($fullname, @suffixlist);
$dirname  = dirname($fullname);

It sounds like dirname($path) is what you are after.

You may also simply use a regex

$path =~ s/\.+$//;
Sign up to request clarification or add additional context in comments.

Comments

1

If all you need is to remove those '..' in the end there're many ways.

For example:

1)

my $str="/temp/bin/usr/..."; 
($str) =~ s/\.+$//; 
print $str;

2)

my $str="/temp/bin/usr/..."; 
$str = substr($str, 0, index($str, "."));
print $str;

3)

my $str="/temp/bin/usr/..."; 
$str = (split /\./, $str)[0];
print $str;

And there're many more!

2 Comments

split and index will fail for paths such as /foo/.bar/....
agree, but OP didn't mention the pattern may vary.
1

To extract part of a path, for example, the first three directories, one way is to use the method splitdir of the module File::Spec, like:

printf "%s\n", join q|/|, (File::Spec->splitdir( $path ))[0..3];

If you want to remove those dots, use a regular expression that matches them after last slash, like:

$path =~ s|(/)\.+\s*$|$1|;

3 Comments

0 .. 2 for three elements. Good solution, though, I will reference it in my answer.
My mistake, the OP meant something else.. I will not reference it. Still a good answer.
@TLP: I wasn't sure either, so I added two different ways to accomplish a task like that. I think that the OP won't have much problem to solve his issue due to the answers he got.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.