Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Remove extra periods (".") in file name 2

Status
Not open for further replies.

NevadaJones

Programmer
Sep 5, 2006
26
How can I remove extra periods from a file name? There could be two or more periods in a file that someone uploads and I want to keep only the last one before the file extention. What I have removes all periods, but I want to check to see if there are more than one and then only keep the last one.

my $filename = "file.soe.that.this.whatever.ext";
$filename =~ s/\.//;
print $filename;
 
One idea:

Code:
my $filename = "file.soe.that.this.whatever.ext";
my (@parts) = split(/\./, $filename);
my $ext = pop(@parts);
$filename = join ("",@parts) . "." . $ext;

That splits it into an array qw(file soe that this whatever ext), pops off $ext ("ext"), then joins the remaining data at "" (nothing), adds a ., then adds $ext ("filesoethathtiswater.ext")

There are probably quicker ways to do this with fewer than 4 lines needed but it's one solution.

-------------
Kirsle.net | Kirsle's Programs and Projects
 
Try this:
Code:
$filename =~ s/\.(?![^.]*$)//g;
 
To use File::Basename for this, you'd need to know what the extension is, no?
 
Thanks for the fast responces. Kirsle's idea works great! I will use it for now, but I will study the other methods also.
 
You can use a regexp like you did in your code ish:

Code:
use File::Basename;
my $filename = 'path/to/file.soe.that.this.whatever.ext';
my ($file,$path,$ext) = fileparse($filename,qr"\.[^.]*$");
print "path = $path\nfile = $file\next = $ext";

then the extra dots could be removed from $file if need be.

- Kevin, perl coder unexceptional!
 
Ah. I missed the part about using a regexp for the extension. Good to know.
 
After checking out ishnid's method, I think it may be much simpler. It works wonderful. Thanks.
 
Ah. I missed the part about using a regexp for the extension.

Ishnid, you're not allowed to miss anything! It's against the laws of nature! I'm cutting my juggler as I type this one last final post...... [sadeyes]


[wink] [wink]

- Kevin, perl coder unexceptional!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top