Forum Moderators: coopster & phranque

Message Too Old, No Replies

Getting rid of spaces online in directory names

Get rid of spaces in folder names

         

DutchFury

6:19 am on Oct 22, 2003 (gmt 0)

10+ Year Member



Hello everybody.

I hope I'm not supposed to be posting this in the *nix forum but here goes:)

I was reading that it was not good to have spaces (%20) in file names. Is there any way to replace spaces with a dash (-) online up on the server? I have a ton of directories with gaps in them, too many to do manually, unless I really have too...

Can a script be made to do this with perl? Or maybe there's a way to do it via telnet with a command like copy?

Any advice would be very appreciated!

Sincerely

DF

jatar_k

1:46 am on Oct 23, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld DutchFury,

You could definitely do this with perl. I could have sworn there was thread around about renaming multiple files recursively but can't for the life of me find it.

Maybe this little bump will catch someone's eye who might be able to offer a little code. ;)

DutchFury

7:02 am on Oct 23, 2003 (gmt 0)

10+ Year Member



Hi and thanks jatar_k,

I was hoping this could be done with perl. I also had a good long search and was surprised to not find this already covered.

Thanks for the "bump":P

If someone could shed some light on this for me I would be sooo grateful! I've given up trying to find a way to do it with unix commands...I think I was barking up the wrong tree there.

sugarkane

9:54 am on Oct 23, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This is actually a bit trickier than I first thought - I have a stock script that changes *filenames* recursively using the File::Find module.

The problem in your situation is that once you change a directory name, paths to subdirectories change, which means that you can't simply find all the directories containing a space, then bulk rename.

I've kludged something together, relying on the fact that if the path to a directory changes the rename will just silently fail, and calling the find routine repeatedly until it can't find any more matching directories.

It seems to work, but maybe someone can come up with a more elegant way of doing it?

#!/usr/bin/perl
use File::Find;

$startpath="/path/to/documents/";
do {
$flag=0;
find sub {
my $foo=$File::Find::name;
if (-d $foo && $foo=~/ /) {
($foo2=$foo)=~s/ /_/g;
rename($foo, $foo2);
$flag=1;
}
},$startpath;
} until ($flag==0);
exit;

Disclaimer - back up your files before running this ;)

DutchFury

2:54 am on Oct 27, 2003 (gmt 0)

10+ Year Member



sugarkane...u da man bro:P

Thanks so much for that code. Saved me atleast a months work!

Webmaster World strikes once again:)

DF