I am trying to extract /temp/bin/usr/ from a variable
$path = /temp/bin/usr/...
using perl. Can someone help me with that ?
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/\.+$//;
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!
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|;
0 .. 2 for three elements. Good solution, though, I will reference it in my answer.
/temp/bin/usr/somedir/dir3/file.txt, or/temp/bin/usr/file.txt? There's a difference.