Reputation: 25
I have the following script to remove spaces from file names:
@echo oN
setlocal enabledelayedexpansion
for /r %%j in (*.*) do (
set filename=%%~nj
set filename=!filename: =!
if not "!filename!"=="%%~nj" ren "%%j" "!filename!%%~xj"
)
Pause
It works great, but I am running into an issue where there will be a duplicate file name when the spaces are removed and the file is skipped. I needed it to append a (2) to the file name (filename(2).doc).
Can someone please help with this? Thanks
Upvotes: 0
Views: 36
Reputation: 14290
You can check for the files existence before the rename. Then you can CALL to a function to number up the file name.
@echo oN
setlocal enabledelayedexpansion
for /r %%G in (*.*) do (
set filename=%%~nG
set filename=!filename: =!
if not "!filename!"=="%%~nG" (
IF EXIST "%~dpG\!filename!%%~xG" (
CALL :NUMBERUP "%%~G" "!filename!"
) ELSE (
ren "%%G" "!filename!%%~xG"
)
)
)
Pause
GOTO :EOF
:NUMBERUP
SET NUM=0
:LOOP
SET /A NUM+=1
IF EXIST "%~dp1\%~2%NUM%%~x1" GOTO LOOP
ren "%~1" "%~n2%NUM%%~x1"
GOTO :EOF
Upvotes: 1