Categories
Perl

perl : Extract filename from full path

Use substr and rindex to extract the name of file from full pathname. Or use basename provided by File::Basename.

To extract the name of the file the quick way is to use substr and rindex commands to strip the path from filename as shown below.

#!/usr/bin/perl

my $path='/path/to/search/filename';
my $fname= substr($path, rindex($path,"/")+1, length($path)-rindex($path,"/")-1);
print "$fnamen";

If you have the luxury of using Perl Packages, then use following solution which is very clean.

#!/usr/bin/perl

use File::Basename;
my $path='/path/to/search/filename';
my $fname = basename($path);
print "$fnamen";