#!/usr/bin/perl -w # # File name, path, extension Perl manipulation # # License: public domain # By Mike Linkovich # link@spacejack.org | www.spacejack.org # use strict; my $dstExt = "png"; # extension to add or change to my $f0 = "c:/dir1\\dir2/file.jpg.name.jpg"; # Original path/file string to test # Note: can handle both / and \ chars my $f1; # intermediate - bare filename my $f2; # changed extension print "\nOriginal Filename: $f0\n"; # Find the last '/' or '\' char: # The regex broken down: # / - search # [\/\\] - for / or \ character # ([^\/\\]*) - followed by 0 or more characters NOT / or \ # $ - search from the end of the string # # If the expression returns true, $1 contains the part # of the string following the first \ or / found. # if( $f0 =~ /[\/\\]([^\/\\]*)$/ ) { $f1 = $1; } else { $f1 = $f0; } print "Bare Filename: $f1\n"; # Now do the same operation to find the last . in the filename: # if( $f1 =~ /\.([^.\/]*)$/ ) { my $ext = $1; print "Extension: $ext\n"; $f2 = $f1; # Substitute the desired extension. # Note we use $ again to substitute from the end of the string. $f2 =~ s/$ext$/$dstExt/; } else { # There was no extension, just tack it on: $f2 = $f1 .= '.' . $dstExt; } print "Changed extension: $f2\n"; exit;