DOS Batch / XP Command prompt file rename to remove spaces. algorithm/code required

Soldato
Joined
22 Aug 2005
Posts
8,968
Location
Clydebank
Hi all

Does anyone have a script or algorithm for searching through a directory tree of files and renaming any that have spaces in the file names and directory names? e.g. to have a _ instead of a space.

The code below does it but it's not great and it's slow (when you're checking 50,000+ files) and I know there must be a better way. I have unixutils binaries, and confirmation or failure of the operation is required, as the rest of my scripts can't proceed unless the files are renamed properly.


Code:
@echo off
REM %1 is top level of dir heirachy to be checked e.g. c:\checkthesefiles\
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION::REMOVE SPACES FROM FILES NAMES

SET UNTMP=C:\UNTMP\
if not exist !UNTMP! MKDIR !UNTMP!


::check for spaces
DIR %1 /B /S | grep "\ ">nul
IF NOT ERRORLEVEL 1 SET ERRNONE=TRUE
IF !ERRNONE!==TRUE ( 
	ECHO [WW] Filenames containing Spaces were found - Removing spaces... 
	FOR /R %1 %%G IN (.) DO ECHO !CD! & CALL :spaceRemove "%%G"
	ECHO.[II] SPACES SUBSTITUTED FOR UNDERSCORES...COMPLETE!
) ELSE (
	ECHO [II] No spaces in filename found. 
)

GOTO:EOF

:spaceRemove
SET SUBDIRLISTORIG=!UNTMP!SUBDIRLISTORIG.TXT
SET SUBDIRLISTNEW=!UNTMP!SUBDIRLISTNEW.TXT
SET SUBDIRLISTCOMB=!UNTMP!SUBDIRLISTCOMB.TXT

CD /D %1
DIR /ON /B > !SUBDIRLISTORIG!
DIR /ON /B | sed "s/ /_/g" > !SUBDIRLISTNEW!
paste -d, !SUBDIRLISTORIG! !SUBDIRLISTNEW! > !SUBDIRLISTCOMB!

FOR /F "tokens=1,2 delims=," %%G IN (!SUBDIRLISTCOMB!) DO (
	IF EXIST "%%G" (
		REM DIR,OLDNAME,NEWNAME
		REM ECHO !CD!,%%G,%%H >> !UNTMP!RENAMELOG.TXT
			REN "%%G" %%H 
		REM
	) ELSE (
		ECHO [EE] ERROR FILE DON'T EXIST
		GOTO:error3 "%%G"
	)
)
GOTO:EOF
 
Last edited:
Back
Top Bottom