1. Perl
  2. File operation
  3. here

Extract the extension from the file name

To extract the extension from the file name, specify the extension with the second argument of fileparse in File::Basename module. To do. The third return value gives you the extension.

use File::Basename;
my ($base_name, $dir, $suffix) = fileparse ($file_txt, '.txt');

You can retrieve the extension by specifying the extension name in the second argument of the fileparse function of the File::Basename module.

You can also use regular expression to specify the extension pattern.

use File::Basename;
my $regex_suffix = qr/\. [^\.]+$/;
my $suffix_txt = (fileparse ($file_txt, $regex_suffix)) [2];

This regular expression retrieves the extension after the last appearing. If you want to match with an extension after the first appearing., Use the regular expression "qw(\ .. + $)".

Example

This is an example to extract the extension from the file name.

use strict;
use warnings;
use File::Basename 'fileparse';

# Extract the extension from the file name.
my $file_txt = 'dir1/dir2/base_name.txt';
my $file_log = 'dir1/dir2/base_name.log';
my $file_bak = 'dir1/dir2/base_name.log.bak';

print "1: Extract the extension from the file name. (Specify the extension name)\n";
my ($base_name, $dir, $suffix) = fileparse ($file_txt, '.txt');
print "\$dir = $dir\n",
  "\$base_name = $base_name\n",
  "\$suffix = $suffix\n\n";

print "2: Extract the extension from the file name. (Specify the extension name pattern)\n";
my $regex_suffix = qr/\. [^\.]+$/;

my $suffix_txt = (fileparse $file_txt, $regex_suffix) [2];
my $suffix_log = (fileparse $file_log, $regex_suffix) [2];
my $suffix_bak = (fileparse $file_bak, $regex_suffix) [2];

print "\$suffix_txt = $suffix_txt\n",
  "\$suffix_log = $suffix_log\n",
  "\$suffix_bak = $suffix_bak\n";

Output

1: Create a file.
C:\Users\kimoto\labo> perl a.pl
1: Extract the extension from the file name. (Specify the extension name)
$dir = dir1/dir2/$base_name = base_name
$suffix = .txt

2: Extract the extension from the file name. (Specify the extension name pattern)
$suffix_txt = .txt
$suffix_log = .log
$suffix_bak = .bak

Related Informatrion