Because I have multiple back-up copies of all files, I use the following batch file to rename files so that I don't have to go into each drive/folder to rename files manually. The batch file works fine for renaming files. However, when renaming folders, sometimes it works, the other time, it generates another folder with the corrected name. When this happens, it doesn't happen to every folders to be renamed, only some of the folders.

Is there something wrong with the batch file? How can it be corrected?

chcp 65001 if exist C:\rename-all-4.txt del c:\rename-all-4.txt SETLOCAL EnableDelayedExpansion (for /f "tokens=1,2 delims=;" %%A in ('"TYPE C:\RENAME-ALL.txt"') do ( echo %%A | find /i "\" if errorlevel 1 ( RENAME "D:\!mypath!%%A" "%%B" RENAME "E:\!mypath!%%A" "%%B" RENAME "\\PC1\D\!mypath!%%A" "%%B" RENAME "\\PC1\E\!mypath!%%A" "%%B" ) ELSE ( echo "found pattern" echo %%A set mypath=%%A echo mypath is !mypath! ) ) ) >> C:\RENAME-ALL-4.txt 2>&1 endlocal CD /D C:\ 

The following is a shortened input file. After running the batch file, the original folder (中国人民银行_files) still exists along with a new folder (中國人民銀行_files).

News\ 中国人民银行_files;中國人民銀行_files 
6

2 Answers

@echo off setlocal enabledelayedexpansion cd /d "%~dp0" & >nul chcp 65001 2>nul del/q /f .\rename-all-4.txt >> .\rename-all-4.txt 2>&1 ( for /f tokens^=1-2^delims^=^; %%a in (' type c:\rename-all.txt')do echo=%%~a|>nul findstr /e \ && ( echo="found pattern" && echo=%%~a set "mypath=%%~a" && call echo=mypath is !mypath! ) || ( ren "d:\!mypath!%%~a" "%%~b" ren "e:\!mypath!%%~a" "%%~b" ren "\\pc1\d\!mypath!%%~a" "%%~b" ren "\\pc1\e\!mypath!%%~a" "%%~b" )) endlocal && CD /D C:\

  • This is an incorrect syntax:
 if errorlevel 1 ... if errorlevel ???? 1 ... errorlevel equal integer :: if !errorlevel! equ 1 ... if %errorlevel% equ 1 ...

Also, try to replace errorlevel condition to operators && and ||




6
SETLOCAL EnableDelayedExpansion (for /f "tokens=1,2 delims=;" %%A in ('"TYPE C:\RENAME-ALL.txt"') do if "%%B"=="" ( echo "found pattern" echo %%A set "mypath=%%A" echo mypath is !mypath! ) ELSE ( RENAME "D:\!mypath!%%A" "%%B" RENAME "E:\!mypath!%%A" "%%B" RENAME "\\USER-PC1\D\!mypath!%%A" "%%B" RENAME "\\USER-PC1\E\!mypath!%%A" "%%B" ) ) >> C:\RENAME-ALL-4.txt 2>&1 endlocal 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy