in reply to rename file
G'day frank1,
Welcome to the Monastery.
Firstly, I think you should define exactly what you mean by extension. For instance, is the extension of archive.tar.gz, .tar.gz or tar.gz or .gz or gz?
As you've already loaded File::Basename, you could use its fileparse() function. This function can be tricky; in particular, the @suffixes argument is a list of patterns. Consider these:
$ perl -E 'use File::Basename; say "|$_|" for fileparse("X.tgz", qw{.g +z .tgz})' |X.| |./| |tgz| $ perl -E 'use File::Basename; say "|$_|" for fileparse("X.tgz", qw{\. +gz \.tgz})' |X| |./| |.tgz|
And the order of the patterns matters. Consider these:
$ perl -E 'use File::Basename; say "|$_|" for fileparse("X.tar.gz", qw +{\.gz \.tgz \.tar\.gz})' |X.tar| |./| |.gz| $ perl -E 'use File::Basename; say "|$_|" for fileparse("X.tar.gz", qw +{\.tgz \.tar\.gz \.gz})' |X| |./| |.tar.gz|
If all you want is the final part after the last '.', or a zero-length string if no such part exists, you can avoid the overhead, and possible frustration, of getting the patterns correct and in the right order, with simple functions which operate on strings (these are typically much faster than regexes but, in the scenario you present, I doubt that will matter much, if at all). This expression will do that for you:
substr $filename, rindex($filename, ".") + 1 || length $filename
And here it is in action, with an assortment of filenames with zero or more '.'s and with and without an actual extension.
$ perl -E ' say "oldfile\t ext \tnewfile"; say "-------\t --- \t-------"; my $newname = "edddd"; for (qw{OPQ.RST .U V. .W. X.Y Z . ..}) { my $ext = substr $_, rindex($_, ".") + 1 || length; say "$_\t|$ext|\t$newname" . (length $ext ? ".$ext" : ""); } ' oldfile ext newfile ------- --- ------- OPQ.RST |RST| edddd.RST .U |U| edddd.U V. || edddd .W. || edddd X.Y |Y| edddd.Y Z || edddd . || edddd .. || edddd
— Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: rename file
by jcb (Parson) on Aug 26, 2020 at 01:26 UTC | |
by kcott (Archbishop) on Aug 26, 2020 at 05:47 UTC |