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. Most files won't have 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: Select all
REM %1 is top level of dir heirachy to be checked e.g. c:\checkthesefiles\
SETLOCAL ENABLEDELAYEDEXPANSION::REMOVE SPACES FROM FILES NAMES
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.
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 ECHO !CD!,%%G,%%H >> !UNTMP!RENAMELOG.TXT
REN "%%G" %%H
) ELSE (
ECHO [EE] ERROR FILE DON'T EXIST