Remove Spaces from file and directory names (perl)

The other day I moved a bunch of files from a windows server to a linux server. The files and directories on the windows server had spaces in them. Linux does not really like spaces in directory and file names.

I went looking around the net and could not find exactly what I wanted, so I took what I could find and modified it. At this point I cannot remember where I got the pieces, but the main brains for this script are not mine. Anyway here it is:

#!/usr/bin/perl -w
# nospace /this/dir /that/dir /those/too

use File::Find;
use strict;
die "usage: nospace dir[s]\n" unless @ARGV;

my %ext;

find(\&remspaces, @ARGV);

sub remspaces {
	return if ($_ eq '.');
	return if ($_ eq '..');
	(my $new = $_) =~ tr/a-zA-Z0-9_.-/_/c;
	my $duplicate = ($new ne $_ and -e $new);
	my $try = $new;
	$ext{"$File::Find::dir/$try"}++ if $duplicate;
	while (my $count = $ext{"$File::Find::dir/$new"}++) {
		(my $with_num = $new) =~ s/(?=\.|$)/_$count/;
		$new = $with_num, last if not -e $with_num;
	$ext{"$File::Find::dir/$try"}-- if $duplicate;
	rename $_ => $new
	or warn "can't rename $_ to $new: $!";

Copy above into a new file, save it as nospace, make it executable and run it by giving it a directory to work on. Thus if your files were in a directory called music call it with:

nospace music

Worked for me.