开发者

How could I get this regex statment to capture just a select piece

I am trying to get the regex in this loop,

my $vmsn_file = $snapshots{$snapshot_num}{"filename"};
my @current_vmsn_files = $ssh->capture("find -name $vmsn_file");
foreach my $vmsn (@current_vmsn_files) {
$vmsn =~ /(.+\.vmsn)/xm;
print "$1\n";
}

to capture the filename from this line,

./vmfs/volumes/4cbcad5b-b51efa39-c3d8-001517585013/MX01/MX01-Snapshot9.vmsn

The only part I want is the part is the actual filename, not the path.

I tried using an expression that was anchored to the end of the line using $ but that did not seem to make any difference. I also tried using 2 .+ inputs, one before the capture group and the one inside the capture group. Once again no luck, also that felt kinda messy to me so I don't want to do that unless I must.

Any idea how I can get at just the file name after the last / to the end of the line?

More can be added as needed, I am not sure what I needed to post to give enough information.

--Update--

开发者_运维知识库

With 5 minutes of tinkering I seemed to have figured it out. (what a surprise)

So now I am left with this, (and it works)

my $vmsn_file = $snapshots{$snapshot_num}{"filename"};
my @current_vmsn_files = $ssh->capture("find -name $vmsn_file");
foreach my $vmsn (@current_vmsn_files) {
$vmsn =~ /.+\/(\w+\-Snapshot\d+\.vmsn)/xm;
print "$1\n";
}

Is there anyway to make this better?


Probably the best way is using the core module File::Basename. That will make your code most portable.

If you really want to do it with a regex and you are based on Unix, then you could use:

$vmsn =~ m%.*/([^/]+)$%;
$file = $1;


well, if you are going to use find command from the shell, and considering you stated that you only want the file name, why not

... $ssh->capture("find -name $vmsn_file -printf \"%f\n\" ");

If not, the simplest way is to split() your string on "/" and then get the last element. No need regular expressions that are too long or complicated.

See perldoc -f split for more information on usage

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜